使用 QQmlApplicationEngine 使来自单独文件的新 window 出现或消失

Make new window from separate file appear or disappear with QQmlApplicationEngine

我正在使用 QQmlApplicationEngine 来加载我的主 window。

QQmlApplicationEngine engine;
engine.load("GUI.qml");

其中 GUI.qml 是我的主要 GUI 文件。我如何从代码中创建和销毁新的 window?据我所知,如果我写engine.load("SecondWindow.qml");,我该如何关闭它?或者我应该从 QML 本身创建和销毁此类对象?

选项 1: 您可以从 QML 执行此操作,请参阅此示例:

import QtQuick 2.12
import QtQuick.Controls 2.5

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480
    title: "Window 1"

    CheckBox {
        id:  cb
        text: "Show Window #2"
    }

    Loader {
        active: cb.checked

        sourceComponent: Component {
            ApplicationWindow {   // Or "SecondWindow"
                visible: true
                width: 640
                height: 480
                title: "Window 2"
            }
        }
    }
}

选项 2: 此外,您可以从 C++ 端控制它,例如:

QML

import QtQuick 2.12
import QtQuick.Controls 2.5

ApplicationWindow {
    id: window
    visible: true
    width: 640
    height: 480
    title: "Window 1"

    Loader {
        active: showWindowFlag

        // Instead of "sourceComponent" you can use
        // source: "SecondWindow.qml"

        sourceComponent: Component {
            ApplicationWindow {
                visible: true
                width: 640
                height: 480
                title: "Window 2"
            }
        }
    }
}

C++

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QTimer>

int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);

    QQmlApplicationEngine engine;

    bool showWindowFlag = false;
    engine.rootContext()->setContextProperty("showWindowFlag", showWindowFlag);  // !!!!

    auto timer = new QTimer(&engine); // Parent will delete timer
    QObject::connect(timer, &QTimer::timeout, [&](){
        showWindowFlag = !showWindowFlag;
        engine.rootContext()->setContextProperty("showWindowFlag", showWindowFlag);
    });

    timer->setInterval(1000);
    timer->setSingleShot(false);
    timer->start();

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}