【发布时间】:2016-12-20 00:08:46
【问题描述】:
遵循此代码:
#include <QDebug>
#include <QCoreApplication>
#include <QThread>
#include <thread>
int main(int argc, char *argv[])
{
// qDebug() << "Whatever"; <- uncommenting this makes the constructor to print a warning
std::thread thread([&]()
{
QCoreApplication app(argc, argv);
qDebug() << "main thread is " << app.thread();
});
thread.join();
qDebug() << "current thread is " << QThread::currentThread();
return 0;
}
它可以编译并且不会崩溃,运行时也不会出现警告。 QCoreApplication 不是在 main() 的线程中创建的。
但是,如果在创建 QCoreApplication 对象之前取消注释 qDebug() 函数调用,则会打印警告:
WARNING: QApplication was not created in the main() thread.
不在main()的线程中创建QCoreApplication合法吗?
【问题讨论】:
-
请告诉我们您为什么要这样做。很可能,没有必要!
-
是的,确实有一个关于这种东西的用途的问题会更好!
-
一种用法是当您在由非 QT 代码加载的共享库中拥有 QT 代码时。您必须在后台线程中创建
QCoreApplication才能使事件处理工作。例如:stackoverflow.com/a/10434948/1464861