Multithreading 如何使用信号&;Qt中用于线程间通信的插槽
我想制作一个应用程序,用户将点击QPushButton,这将触发一个辅助线程,该线程将向主窗口中的QListWidget添加一些文本。但是由于一个我无法理解的原因,尽管从线程到主窗口的信号被发出,但它从未到达目的地。可能是因为连接失败了。但这里发生这种情况的原因是我的代码(我的应用程序是使用Visual Studio 2010编译的): mythread.hMultithreading 如何使用信号&;Qt中用于线程间通信的插槽,multithreading,qt,slot,Multithreading,Qt,Slot,我想制作一个应用程序,用户将点击QPushButton,这将触发一个辅助线程,该线程将向主窗口中的QListWidget添加一些文本。但是由于一个我无法理解的原因,尽管从线程到主窗口的信号被发出,但它从未到达目的地。可能是因为连接失败了。但这里发生这种情况的原因是我的代码(我的应用程序是使用Visual Studio 2010编译的): mythread.h #ifndef MY_THREAD_H #define MY_THREAD_H #include <QThread> #inc
#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
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
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();
}
两件事:
Qstring
必须更改为Qstring
QString&
accross线程。有两种方法可以解决此问题:
QString
而不是QString&
QString&
可用但是,在处理线程时。如果您不打算修改参数,首先使用
const
限定符作为参数。在修复了connectionSLOT(receiveMsg(Qstring&))
中的输入错误,并将信号和SLOT签名更改为const引用后,一切正常我尝试添加exec()调用,但没有发生任何事。此外,Qt文档中的Mandelbrot示例不使用exec()。第二个connect()调用返回false。我正试图找出原因。请看@Tim Meyer你能把“http”改成“https”吗?因此,指针将直接工作。如果您的连接中有输入错误:SLOT(receiveMsg(Qstring&)
应该是SLOT(receiveMsg(Qstring&)
。您应该在调试器或控制台中启动应用程序,以查看Qt在stdout和stderr上写了什么
#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);
}
#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();
}
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
# Input
HEADERS += mydialog.h mythread.h
SOURCES += find.cpp mydialog.cpp mythread.cpp