我想創建一個應用程序,用戶將點擊一個QPushButton,這將觸發一個輔助線程,它將向主窗口中的QListWidget添加一些文本。但由於我無法弄清楚的原因,雖然從線程到主窗口的信號被髮射出去,但它永遠不會到達目的地。可能因爲連接失敗。但是,爲什麼出現這種情況,這裏是我的代碼(我的應用程序是使用Visual Studio 2010編譯):如何使用Qt中的信號和插槽進行線程間通信
mythread.h
#ifndef MY_THREAD_H
#define MY_THREAD_H
#include <QThread>
#include <QString>
class mythread:public QThread
{
Q_OBJECT
public:
void setName(QString& name);
signals:
void sendMsg(QString& msg);
protected:
void run();
private:
QString m_name;
QString msg;
};
#endif
mythread.cpp
#include "mythread.h"
void mythread::setName(QString& name)
{
m_name=name;
}
void mythread::run()
{
msg="Hello "+m_name;
emit sendMsg(msg);
}
mydialog.h:
#ifndef MY_DIALOG_H
#define MY_DIALOG_H
#include <QtGui>
#include "mythread.h"
class mydialog:public QDialog
{
Q_OBJECT
public:
mydialog();
public slots:
void receiveMsg(QString& msg);
void fillList();
private:
QListWidget list1;
QPushButton btn1;
QGridLayout layout;
mythread thread;
};
#endif
mydialog.cpp:
#include "mydialog.h"
mydialog::mydialog()
{
layout.addWidget(&list1,0,0);
btn1.setText("Find");
layout.addWidget(&btn1,0,1);
setLayout(&layout);
QString myname="leonardo";
thread.setName(myname);
connect(&btn1,SIGNAL(clicked()),this,SLOT(fillList()));
connect(&thread,SIGNAL(sendMsg(QString&)),this,SLOT(receiveMsg(Qstring&)));
}
void mydialog::fillList()
{
thread.start();
}
void mydialog::receiveMsg(QString& msg)
{
list1.addItem(msg);
}
find.cpp:
#include <QApplication>
#include "mydialog.h"
int main(int argc,char* argv[])
{
QApplication app(argc,argv);
mydialog window;
window.setWindowTitle("Find");
window.show();
return app.exec();
}
find.pro:
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
# Input
HEADERS += mydialog.h mythread.h
SOURCES += find.cpp mydialog.cpp mythread.cpp
在連接中有一個錯字:'SLOT(receiveMsg(Qstring&))'應該是'SLOT(receiveMsg(QString&))'。您應該在調試器或控制檯中啓動您的應用程序,以查看在stdout和stderr上寫入了哪些Qt –