如何解决QObject ::〜QObject:无法从另一个线程停止计时器
我有这个非常简单的Qt代码:
void thread_func()
{
int a1 = 1;
const char* a2[] = { "dummy_param" };
QApplication app(a1,(char**)a2);
QMessageBox msg(QMessageBox::NoIcon,"MyTitle","Foo bar Foo bar",QMessageBox::Ok);
msg.exec();
}
如果我在main
的{{1}}中调用上述函数,则会弹出对话框:
std::thread
...但是当我关闭它时,我收到警告消息:
int main()
{
std::thread t(thread_func);
t.join();
}
我检查了QObject::~QObject: Timers cannot be stopped from another thread
实例和QApplication
的线程亲和力是否相同。直接从我的msg
调用thread_func
函数(而不创建main()
)删除该消息。
我正在Windows 10上使用Qt 5.15.1。
我在这里想念什么?谢谢
解决方法
警告消息说明了一切。使用信号/插槽机制来完成同样的事情。
#include <QApplication>
#include <QMessageBox>
#include <QObject>
#include <QThread>
#include <QWidget>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(){}
public slots:
void displayMessageBox()
{
QMessageBox msg(QMessageBox::NoIcon,"MyTitle","Foo bar Foo bar",QMessageBox::Ok);
msg.exec();
this->close();
}
};
class Worker : public QObject
{
Q_OBJECT
public:
explicit Worker() {}
void start() { emit askForMessageBox(); }
signals:
void askForMessageBox();
};
int main(int argc,char *argv[])
{
QApplication a(argc,argv);
Widget *widget;
Worker *worker;
QThread *thread(nullptr);
widget = new Widget();
worker = new Worker();
thread = new QThread(nullptr);
QObject::connect(worker,&Worker::askForMessageBox,widget,&Widget::displayMessageBox);
QObject::connect(thread,&QThread::started,worker,&Worker::start);
widget->show();
worker->moveToThread(thread);
thread->start();
return a.exec();
}
,
不允许直接在主线程(GUI thead)外部操作Qt GUI。您可以发出信号。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。