我使用的是QT框架。我使用SIGNAL-SLOT已经有一段时间了。我喜欢它。:-(但当我使用QThread时,我无法使其工作。我总是使用"moveToThread(QThread…("函数创建新线程。有什么建议吗?:-(
错误消息为:
对象:connect:中没有这样的插槽连接::acceptNewConnection(QString,int(。。\MultiMITU600\mainwindow.cpp:14对象::连接:(发件人名称:"MainWindow"(
我读过类似的问题,但这些问题与QThread无关。
谢谢David
编辑:您要求提供源代码这里有一个:
这是代码:
包含信号和新线程的主类:
主窗口标题:
class MainWindow : public QMainWindow
{
…
QThread cThread;
MyClass Connect;
...
signals:
void NewConnection(QString port,int current);
…
};
上面类的构造函数:.cpp
{
…
Connect.moveToThread(&cThread1);
cThread.start(); // start new thread
….
connect(this,SIGNAL(NewConnection(QString,int)),
&Connect,SLOT(acceptNewConnection(QString,int))); //start measuring
…
}
包含新线程和SLOT的类标题:
class MyClass: public QObject
{
Q_OBJECT
….
public slots:
void acceptNewConnection(QString port, int current);
}
以及上面类的.cpp文件:
void MyClass::acceptNewConnection(QString port, int current){
qDebug() << "This part is not be reached";
}
最后,我在建立连接的类中使用emit:
void MainWindow::on_pushButton_3_clicked()
{
…
emit NewConnection(port, 1);
}
class MyClass : public QObject
{
Q_OBJECT
public:
explicit MyClass(QObject *parent = 0);
public slots:
void acceptConnection(QString port, int current) {
qDebug() << "received data for port " << port;
}
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0) : QMainWindow(parent) {
myClass.moveToThread(&thread);
thread.start();
connect(this, SIGNAL(newConnection(QString,int)), &myClass, SLOT(acceptConnection(QString,int)));
emit newConnection("test", 1234);
}
signals:
void newConnection(QString, int);
private:
QThread thread;
MyClass myClass;
};
输出:received data for port "test"
您的void MainWindow::on_pushButton_3_clicked()
插槽是否连接到信号?
此外,为了代码的清晰性和可读性,请保留已建立的命名约定,并对对象实例、成员对象和方法使用小写。