在我的应用程序中,我想通过 C++ 代码创建另一个带有 QML UI 的窗口。
我知道可以使用 QML 窗口类型创建另一个窗口,但我需要从 C++ 代码中获得同样的东西。
到目前为止,我设法将我的附加 qml 文件加载到 QQmlComponent 中:
QQmlEngine engine;
QQmlComponent component(&engine);
component.loadUrl(QUrl(QStringLiteral("qrc:/testqml.qml")));
if ( component.isReady() )
component.create();
else
qWarning() << component.errorString();
如何在单独的窗口中显示它?
最佳答案
您可以使用单个 QQmlEngine
来实现。按照您的代码,您可以执行以下操作:
QQmlEngine engine;
QQmlComponent component(&engine);
component.loadUrl(QUrl(QStringLiteral("qrc:/main.qml")));
if ( component.isReady() )
component.create();
else
qWarning() << component.errorString();
component.loadUrl(QUrl(QStringLiteral("qrc:/main2.qml")));
if ( component.isReady() )
component.create();
else
qWarning() << component.errorString();
不过我更喜欢QQmlApplicationEngine
。此类结合了 QQmlEngine
和 QQmlComponent
以提供一种方便的方式来加载单个 QML 文件。因此,如果您有机会使用 QQmlApplicationEngine
,您的代码行会更少。
例子:
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
engine.load(QUrl(QStringLiteral("qrc:/main2.qml")));
return app.exec();
我们也可以使用QQuickView
。 QQuickView
仅支持加载从 QQuickItem
派生的根对象,因此在这种情况下,我们的 qml
文件不能以 QML 类型 开头ApplicationWindow
或 Window
就像上面的例子。所以在这种情况下,我们的 main
可能是这样的:
QGuiApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl("qrc:/main.qml"));
view.show();
QQuickView view2;
view2.setSource(QUrl("qrc:/main2.qml"));
view2.show();
return app.exec();
关于c++ - 从 C++ 代码创建单独的 QML 窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35127772/