问题:在自定义线程中创建窗口,ASSERT failure in QWidget: "Widgets must be created in the GUI thread."

1、构建一个窗口启动器对象;

class GuiLauncher : public QObject
{
    Q_OBJECT
public:
    explicit GuiLauncher(QObject *parent = nullptr);

    bool event(QEvent *event) override;

signals:

};
#include "guilauncher.h"
#include <QDialog>
#include <QEvent>

GuiLauncher::GuiLauncher(QObject *parent) : QObject(parent)
{

}

bool GuiLauncher::event(QEvent *event)
{
    //int ntype = event->type();
    if (event->type() == QEvent::User)
    {
        //create gui object.
        QDialog dlg;
        return true;
    }
    return QObject::event(event);
}

 

2、将窗口启动器对象移动到GUI线程;

3、利用Qt的事件处理机制,自定义一个事件QEvent::User

4、在窗口启动器的事件处理函数中,处理QEvent::User事件,创建需要创建的窗口;

 

5、在自定义线程中创建窗口启动器对象;

GuiLauncher* launcher = new GuiLauncher;
launcher->moveToThread(QApplication::instance()->thread());
QCoreApplication::postEvent(launcher, new QEvent(QEvent::User));

参考:https://www.it1352.com/456859.html

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐