从 Slot qt 创建时 MessageDialog 冻结

MessageDialog freezes when created from Slot qt

我正在尝试显示来自工作线程的消息对话框。使用插槽和信号是通信 with/calling QML 对象的标准方式,但是当出现对话框时,它的按钮是 unclickable/not 响应。

main.cpp

tester* test = new tester;
QtConcurrent::run(test,tester::testFunction);

tester.cpp

#include "tester.h"
#include <QQmlEngine>
#include <QQmlComponent>

tester::tester(QObject *parent) : QObject(parent) {
    QObject::connect(this,SIGNAL(show()),this,SLOT(showSlot()));
}
void tester::testFunction() {
    emit show();
}
void tester::showSlot(){
    QQmlEngine engine;
    QQmlComponent component(&engine, QUrl(QLatin1String("qrc:/BlockingDialog.qml")));
    QObject *object = component.create();
    QMetaObject::invokeMethod(object, "open");
}

tester.h

#include <QObject>

class tester : public QObject{
    Q_OBJECT
public:
    explicit tester(QObject *parent = 0);
    void testFunction();
signals:
    void show();
public slots:
    void showSlot();
};

BlockingDialog.qml

import QtQuick 2.7
import QtQuick.Dialogs 1.2

MessageDialog {
    id:dialog    
}

您正在 showSlot() 中的堆栈上创建 QML 引擎,因此它将在函数完成时被销毁。加载 QML 文件的典型方法是在 main().

中的堆栈上创建 QML 引擎