使用ApplicationWindow时热重载QML

时间:2019-03-13 16:48:55

标签: qt qml reload hot-reload applicationwindow

使用ApplicationWindow时,有人能够热重载所有QML文件吗?我发现了一些示例,例如https://qml.guide/live-reloading-hot-reloading-qml/https://www.slideshare.net/ICSinc/how-best-to-realize-a-runtime-reload-of-qml,但是大多数情况下它们使用Loader,并且由于ApplicationWindow必须是根项,所以这是行不通的(没有窗口出现)只是重新加载所有QML内容。

我尝试过:

ApplicationWindow {
    id: window
    visibility: "FullScreen"

    Shortcut {
        sequence: "F5"
        context: Qt.ApplicationShortcut
        onActivated: {
            window.close();
            app.loadQml();
        }
    }
    ...
}

其中app是我在C ++端设置的上下文属性,该函数可以:

void App::loadQml()
{
    qml_engine_.clearComponentCache();
    // Use "qrc:/Main.qml" for Qt Resource System.
    // Use "Main.qml" for file system.
    qml_engine_.load(QUrl(QStringLiteral("Main.qml")));
}

这种代码只能工作一次,窗口会消失并重新出现,但是快捷方式只能工作一次,而不会第二次...

任何想法如何实现这一目标?

1 个答案:

答案 0 :(得分:2)

这是我所做的,并且工作正常: main.cpp:

urn:oasis:names:tc:xacml:1.0:subject:subject-Name

app.cpp:

subjectName

app.h:

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "app.h"

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

    QApplication app(argc, argv);

    QQmlApplicationEngine engine;

    App appp;
    appp.setEngine(&engine);

    engine.rootContext()->setContextProperty("app", &appp);

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

main.qml:

#include "app.h"

App::App(QObject *parent): QObject (parent)
{

}

App::~App(){}

void App::loadQml()
{
    m_engine->load(QUrl(QStringLiteral("qrc:/main.qml")));
}