1. 程式人生 > 其它 >Qt 執行緒中發射訊號無響應問題

Qt 執行緒中發射訊號無響應問題

下面是正常情況程式碼,將介面物件類的this指標傳入到執行緒中,在一個工作者執行緒中呼叫此類的訊號,物件的槽函式能夠正常響應。

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtConcurrent>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(this, &MainWindow::testsignal, this
, &MainWindow::ontestSignal); QtConcurrent::run([this]{ emit testsignal(); }); } MainWindow::~MainWindow() { delete ui; } void MainWindow::ontestSignal() { ui->pushButton->setText("test"); ui->pushButton->setStyleSheet("background-color: red"); }

執行後效果:

  但是當把程式碼修改為下面這樣時,線上程中傳送訊號,介面物件不會響應訊號,而在介面物件中直接呼叫則可以正常響應。

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(this, &MainWindow::testsignal, this, &MainWindow::ontestSignal);

    QtConcurrent::run([this]{
        emit testsignal(MyColor::Red);
    });
}

MainWindow::
~MainWindow() { delete ui; } void MainWindow::ontestSignal(MyColor clr) { ui->pushButton->setText("test"); ui->pushButton->setStyleSheet("background-color: red"); } void MainWindow::on_pushButton_clicked() { emit testsignal(MyColor::Red); }

效果如下:

  最開始試了各種方法,通過QThread,在QThread中定義訊號,再繫結到介面物件,但無論怎麼搞槽函式都不會響應。最後快崩潰的時候發現輸出中有這樣一句話:

 

  然後豁然開朗,原來是訊號中用到QT不認識的型別,添加註冊下就OK了

qRegisterMetaType<MyColor>("MyColor");