如何在主线程外创建QtQuick窗口 [英] How to create QtQuick window outside the main thread

查看:43
本文介绍了如何在主线程外创建QtQuick窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是一个主线程,它实例化一个扩展 QQuickView 的类并将其移动到第二个线程.

What I'd like to have is a main thread that instantiates a class that extends QQuickView and moves it to a second thread.

理想情况下,我想做这样的事情:

Ideally, I would like to do something like this:

ma​​in.cpp

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    MyClass myClassObj;

    myClassObj.init();

    return 0;
}

MyClass.cpp

void init()
{
    MyQtQuickClass view;

    QThread* GUIthread = new QThread(this);

    view.moveToThread(GUIthread);
    QObject::connect(GUIthread, SIGNAL(started()), &view, SLOT(init()));

    GUIthread.start();
}

MyQtQuickCLass.cpp

void init()
{
    QQmlContext* rootContext = this->rootContext();

    // Setup view code here

    this->show();

    QGuiApplication::instance()->exec();
}

有了这样的东西,我得到了这个错误:QQmlEngine:非法尝试连接到与 QML 引擎 QQmlEngine(0xdf6e70) 不同线程中的 QQmlContext(0x120fc60).

With something like this I get this error: QQmlEngine: Illegal attempt to connect to QQmlContext(0x120fc60) that is in a different thread than the QML engine QQmlEngine(0xdf6e70).

有解决方法吗?或者直接在第二个线程中创建QML引擎的方法?

Is there a workaround? Or a way to create the QML engine directly in the second thread?

推荐答案

如果你想让 QQuickView 存在于 main() 线程之外,那么你必须:

If you want a QQuickView to live outside the main() thread, then you must:

  1. 创建一个新的std::thread(不是QThread,因为它是一个QObject,所以它不能在你之前创建QGuiApplication)
  2. 在该线程中运行 init() 函数.让它实例化您的 QGuiApplication 并启动事件循环.
  3. 也在该线程中创建您的 QQuickView.
  4. 确保仅从该线程访问所有 GUI 对象.
  5. 确保您的 main() 线程在您的 QGuiApplication 在其他线程中创建之前不会创建任何 QObject .
  1. Create a new std::thread (NOT a QThread, because it is a QObject so it mustn't be created before your QGuiApplication)
  2. Run an init() function in that thread. Let it instantiate your QGuiApplication and start the event loop.
  3. Create your QQuickView in that thread too.
  4. Ensure that all of your GUI objects are accessed from that thread only.
  5. Ensure that your main() thread doesn't create any QObjects until after your QGuiApplication has been created in your other thread.

请参阅如何避免使用 Qt 应用.exec() 阻塞主线程了解更多详情.

这篇关于如何在主线程外创建QtQuick窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆