Qt:没有从第二个线程调用插槽

时间:2018-03-25 17:09:25

标签: c++ qt signals-slots

我想从第二个线程更新UI,我已经创建了将通过信令从其他线程调用的插槽,但不知何故它不是从其他线程调用的。以下是代码:

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);
}

用法:

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 ????
}

注意:当我传递连接类型Qt::DirectConnectoin时,它正在运行,但问题是它不是GUI线程。

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

主要

#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();
}

1 个答案:

答案 0 :(得分:0)

经过大量尝试并逐行检查代码后,我终于找到了问题。原因是覆盖了event()的{​​{1}}函数,QWidget函数的返回值为event(),因此如果您返回bool,则可以运行良好,不会抛出任何运行时或编译时错误。但它会阻止true事件发生。

所以不 signal-slot,但return true则会解决问题。