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");
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!