How to use signals & slots in Qt for inter-threading communication?
I want to make an application where the user will hit a QPushButton and this will trigger a secondary thread which will add some text to a QListWidget in the main window. But for a reason that I cannot figure out ,although the signal from the thread to the main window is emitted it never reaches the destination. Probably because the connection fails. But why this happens? Here is my code(my application is compiled using Visual Studio 2010):
class mythread:public QThread
void setName(QString& name);
void sendMsg(QString& msg);
void mythread::setName(QString& name)
class mydialog:public QDialog
void receiveMsg(QString& msg);
void mydialog::receiveMsg(QString& msg)
int main(int argc,char* argv)
@TEMPLATE = app
DEPENDPATH += .
INCLUDEPATH += .
HEADERS += mydialog.h mythread.h
SOURCES += find.cpp mydialog.cpp mythread.cpp@
You have fallen victim to a common mistake. "You're doing it wrong":http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/. Don't subclass QThread but rather use the new "best practise for QThreads":http://developer.qt.nokia.com/wiki/QThreads_general_usage.
I think your problem is that you forgot to call exec() in your run() function implementation. Therefor your thread doesn't have an eventloop, and therefor the signal is not emitted. It's just one of the many pitfalls that often arise when people follow the old approach of subclassing QThread rather than just moving a worker object to a QThread. There is also a "doc note in the QThread reference":http://qt-project.org/doc/qt-4.8/QThread.html#notes.
Hi! This approach is vicious:
You should always allocate QObjects dynamically (using new):
// in constructor
list1 = new QListWidget();
btn1 = new QPushButton();
layout = new QGridLayout();@
This is because you usually add widgets to a parent widget making them its children and QObject automatically deletes its children.
Therefore, anything that becomes someone's child should be allocated dynamically using operator new.
Although in your particular case you didn't explicitly set parent to your button, listwidget and layout but you used addWidget and setLayout on them which implicitly made them dialog's children.
"Official docs on QObject destructor":http://qt-project.org/doc/qt-4.8/qobject.html#dtor.QObject