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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM