简体   繁体   中英

Qt: slots are not being called from the second thread

I want to update UI from the second thread, I have created slots which are going to be called from other thread by signaling, but somehow it is not being called from the other thread. Below is the code:

WorkerThread.h

class WorkerThread: public QObject
{
    Q_OBJECT
public:
    WorkerThread();
    ~WorkerThread();

public slots:
    void onStart();
signals:
    void sendMessage(const QString& msg, const int& code);
};

WorkerThread.cpp

#include "workerwhread.h"

WorkerThread::WorkerThread(){}

void WorkerThread::onStart(){
    emit sendMessage("start", 100);
}

Usage:

MyWidget.h

namespace Ui {
class MyWidget;
}

class MyWidget: public QWidget
{
    Q_OBJECT

public:
    explicit MyWidget(QWidget *parent = 0);
    ~MyWidget();
private slots:
    void onGetMessage(const QString &msg, const int& code);
private:
    Ui::MyWidget *ui;
    QThread *thread = nullptr;
    WorkerThread *wt = nullptr;
};

MyWidget.cpp

MyWidget::MyWidget(QWidget *parent) : QWidget(parent), ui(new Ui::MyWidget)
{
    ui->setupUi(this);
    wt = new WorkerThread;
    thread = new QThread;

    connect(thread, &QThread::finished, wt, &QObject::deleteLater);
    connect(ui->btStart, &QPushButton::clicked, wt, &WorkerThread::onStart);
    connect(wt, &WorkerThread::sendMessage, this, &MyWidget::onGetMessage);
    wt->moveToThread(thread);
    thread->start();
}
void MyWidget::onGetMessage(const QString &msg, const int& code)
{
    qDebug() << "message" << msg; // this never being called ????
}

Note: When I pass the connection type Qt::DirectConnectoin , then it is working, but the problem is it is not the GUI thread.

connect(wt, &WorkerThread::sendMessage, this, &MyWidget::onGetMessage, Qt::DirectConnection);

Main

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    w.setWindowIcon(QIcon(":/icons/system.png"));
    return a.exec();
}

After a lot of trying and checking the code line by line, I finally found the problem. The reason was with overriding the event() function of QWidget , the return value of event() function is bool , so if you return a true it is OK and working well without throwing any runtime or compile-time error. But it will prevent signal-slot events to happen.

So NOT return true , but return QWidget::event(event); then it will slove the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM