How to connect the signal and slot in multi-thread program?
-
The mainwindow.cpp:
@#include "ui_mainwindow.h"
#include <QtCore>/* ****** Thread part ****** */
myThread::myThread(QObject *parent)
: QThread(parent)
{
}void myThread::run()
{
while(1){
qDebug("thread one----------");
emit threadSignal1();
usleep(100000);
}
exec();
}myThread2::myThread2(QObject *parent)
: QThread(parent)
{
}void myThread2::run()
{
while(1){
qDebug("thread two");
emit threadSignal2();
usleep(100000);
}
exec();
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);onethread = new myThread(this); onethread->start(QThread::NormalPriority); twothread = new myThread2(this); twothread->start(QThread::NormalPriority); connect(onethread, SIGNAL(onethread->threadSignal1()), this, SLOT(mySlot1())); connect(twothread, SIGNAL(threadSignal2()), this, SLOT(mySlot2()),Qt::QueuedConnection);
}
void MainWindow::mySlot1()
{
ui->textEdit1->append("This is thread1");
}void MainWindow::mySlot2()
{
ui->textEdit1->append("This is thread2");
}MainWindow::~MainWindow()
{
delete ui;
}void MainWindow::on_pushButton_clicked()
{
ui->textEdit1->append("textEdit1");
ui->textEdit2->append("textEdit2");
}@The mainwindow.h:
@#define MAINWINDOW_H
#include <QMainWindow>
#include <QThread>namespace Ui {
class MainWindow;
}class myThread : public QThread
{
Q_OBJECTpublic:
myThread(QObject *parent = 0);
void run();signals:
void threadSignal1();
};class myThread2 : public QThread
{
Q_OBJECTpublic:
myThread2(QObject *parent = 0);
void run();signals:
void threadSignal2();
};class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void mySlot1();
void mySlot2();private slots:
void on_pushButton_clicked();private:
Ui::MainWindow *ui;
myThread *onethread;
myThread2 *twothread;
};#endif // MAINWINDOW_H@
Please check the above code. It can give the qDebug output normally while the textEdit1/2 have no any output. And it seems to be a multi-thread signal/slot connect issue. Who can help? Thanks!
-
You provide the code - it is good. But I can not understand what you want?
In mainwindow.h file put slots in the public section:@
public slots:
void mySlot1();
void mySlot2();
@Without this, these methods are not slots, so do not working in connection.
-
Yes, you are right. This is the root cause! After correcting it, the code can work now. Thank you!
-
Glad to help!
Add [Solved] in the title of the stream.