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();
}

如果我在std::thread中从main调用上述函数,它会弹出对话框:

int main()
{
std::thread t(thread_func);
t.join();
}

但当我关闭它时,我会收到警告信息:

QObject::~QObject: Timers cannot be stopped from another thread

我已经检查了QApplication实例和msg的线程亲和性是否相同。直接从我的main()调用thread_func函数(不创建std::thread(会删除该消息。

我在Windows 10上使用Qt 5.15.1。

我在这里错过了什么?感谢

不允许直接在主线程(GUI thead(之外操作Qt GUI。你可以发射信号。

警告消息说明了一切。使用信号/插槽机制来完成同样的事情。

#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();
}

最新更新