在main()的线程中创建QCoreApplication对象是否合法?

时间:2016-08-12 22:05:43

标签: c++ qt

遵循以下代码:

#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是否合法?

1 个答案:

答案 0 :(得分:1)

documentation开始,这是合法的,但不推荐:

  

通常,我们建议您尽早在main()函数中创建QCoreApplication,QGuiApplication或QApplication对象