【问题标题】:Is it legal to create QCoreApplication object not in main()'s thread?在 main() 的线程中创建 QCoreApplication 对象是否合法?
【发布时间】: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

标签: c++ qt


【解决方案1】:

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

一般来说,我们建议您尽早在 main() 函数中创建 QCoreApplication、QGuiApplication 或 QApplication 对象

【讨论】:

  • 读起来略有不同,我认为这意味着实例是在主线程中创建的。
  • @JonHarper 创建*Application 的实例由用户负责,因此文档不能做任何其他事情,只能推荐一些东西。正如OP所说,他甚至在另一个线程中也成功地创建了它,所以我猜答案中的那个是一个有意义的解释。总之,观点不错。
  • @skypjack,我听说你无法让事件循环在 Mac OS 的非主线程中运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-31
  • 2021-11-14
  • 1970-01-01
  • 2015-01-05
  • 2014-10-10
  • 2014-10-08
  • 1970-01-01
相关资源
最近更新 更多