gpt4 book ai didi

c++ - 如何在不同的 QT 线程中创建一个窗口?

转载 作者:IT老高 更新时间:2023-10-28 22:25:08 27 4
gpt4 key购买 nike

我有一个应用程序,其中每个线程(主线程除外)都需要创建自己的窗口。我尝试创建一个线程,然后在 run 函数中调用 this->exec()。但是,在我进行该调用之前,我收到了一个错误:ASSERT failure in QWidget: "Widgets must be created in the GUI thread."

我想弹出一个消息窗口。问题是源有多个线程,每个线程可能需要弹出自己的消息。

最佳答案

如果您需要在不同的(非主)线程中创建 QWidget(或其他一些 gui 组件),您可以通过这种方式实现它:

  • 创建包含 gui 组件的简单包装器:

    // gui component holder which will be moved to main thread
    class gui_launcher : public QObject
    {
    QWidget *w;
    // other components
    //..
    public:
    virtual bool event( QEvent *ev )
    {
    if( ev->type() == QEvent::User )
    {
    w = new QWidget;
    w->show();
    return true;
    }
    return false;
    }
    };
  • 在主线程中创建 QApplication 对象

  • 另一个线程体:

    ..
    // create holder
    gui_launcher gl;
    // move it to main thread
    gl.moveToThread( QApplication::instance()->thread() );
    // send it event which will be posted from main thread
    QCoreApplication::postEvent( &gl, new QEvent( QEvent::User ) );
    ..
  • 要开心,:)

关于c++ - 如何在不同的 QT 线程中创建一个窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9777911/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com