正确重新加载 QQmlApplicationEngine [英] Properly reloading a QQmlApplicationEngine

查看:55
本文介绍了正确重新加载 QQmlApplicationEngine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于 QML 的应用程序,它从文件系统加载 main.qml 文件,如下所示:

I have a QML-based app that loads a main.qml file from the file system like this:

myEngine->load("main.qml");

这很好用,但我想重新加载"引擎,以防 main.qml 被更新的版本替换.

This works fine, but I'd like to "reload" the engine in case the main.qml was replaced with a newer version.

到目前为止,我尝试的是再次调用 load(),假设引擎会像在其他 Qt 类中一样自动重置自己.

What I tried so far was calling load() again, assuming that the engine will automatically reset itself like in other Qt classes.

不幸的是,情况并非如此.如果我再次调用该方法,将出现另一个窗口,其中包含更新的 qml 文件的内容,而原始窗口保持打开状态并继续显示旧的 qml 文件.

Unfortunately this is not the case. If I call the method again, another window will appear with the contents of the updated qml file, while the original window stays open and continues to display the old qml file.

为了解决这个问题,我尝试调用 load(QUrl()),然后调用 clearComponentCache() 和对新文件的最终加载调用.这会产生相同的效果.

To fix this I tried to call load(QUrl()), followed by clearComponentCache() and a final load call for the new file. This results in the same effect.

任何想法如何在应用程序运行时正确"重新加载 QML 引擎?

Any ideas how I can "properly" reload a QML engine while the application is running?

推荐答案

我会尝试将 myEngine 存储为堆上的指针,并在调用 quit().然后你可以重构它以获得新版本的 QML 文件.

I would try storing myEngine as a pointer on the heap, and deleting it after calling quit(). Then you can reconstruct it to get the new version of the QML file.

如果您出于某种原因不想这样做(例如,因为您想保留窗口或其他原因),您可以尝试使用 Loader 并以这种方式加载 QML 文件.您的 main.qml 将如下所示:

If you don't want to do this for some reason (e.g. because you want to keep the window around or whatever), you might try using a Loader and loading the QML file that way. Your main.qml would then look something like this:

import QtQuick 2.0

Loader {
     source: "changing.qml"
}

当您检测到 changeing.qml 已更改时,只需切换 active 属性来触发文件的重新加载.

Whenever you detect that changing.qml has changed, just toggle the active property of Loader to trigger a reload of the file.

这篇关于正确重新加载 QQmlApplicationEngine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆