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

 

posted @   菜鸟_IceLee  阅读(1104)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示