从 C++ 代码创建单独的 QML 窗口

Ale*_*nko 3 c++ qt qml qtquick2 qqmlcomponent

在我的应用程序中,我想从 C++ 代码创建另一个带有 QML UI 的窗口。

我知道可以使用 QML Window 类型创建另一个窗口,但我需要 C++ 代码中的相同内容。

到目前为止,我设法将我的附加 qml 文件加载到 QQmlComponent 中:

QQmlEngine engine;
QQmlComponent component(&engine);
component.loadUrl(QUrl(QStringLiteral("qrc:/testqml.qml")));
if ( component.isReady() )
    component.create();
else
    qWarning() << component.errorString();
Run Code Online (Sandbox Code Playgroud)

如何在单独的窗口中显示它?

Tar*_*rod 5

您可以使用单个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();
Run Code Online (Sandbox Code Playgroud)

我更喜欢QQmlApplicationEngine。此类结合了QQmlEngineQQmlComponent以提供一种方便的方法来加载单个 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();
Run Code Online (Sandbox Code Playgroud)

我们也可以使用QQuickView. QQuickView仅支持加载源自的根对象,QQuickItem因此在这种情况下,我们的qml文件不能以 QML 类型ApplicationWindowWindow以上示例中的类型开头。所以在这种情况下,我们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();
Run Code Online (Sandbox Code Playgroud)