Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create separate QML window from C++ code

In my application I want to create another window with QML UI from C++ code.

I know it's possible to create another window using QML Window type, but I need the same thing from C++ code.

So far I managed to load my additional qml file into QQmlComponent:

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

How do I display it in a separate window?

like image 722
Aleksei Petrenko Avatar asked Dec 07 '25 05:12

Aleksei Petrenko


2 Answers

You can achieve that using a single QQmlEngine. Following your code, you could do something like this:

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();

I prefer QQmlApplicationEngine though. This class combines a QQmlEngine and QQmlComponent to provide a convenient way to load a single QML file. So you would have fewer lines of codes if you have the opportunity of using QQmlApplicationEngine.

Example:

QGuiApplication app(argc, argv);

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
engine.load(QUrl(QStringLiteral("qrc:/main2.qml")));

return app.exec();

We could also use QQuickView. QQuickView only supports loading of root objects that derive from QQuickItem so in this case our qml files couldn't start with the QML types ApplicationWindow or Window like in the examples above. So in this case, our main could be something like this:

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();
like image 133
Tarod Avatar answered Dec 09 '25 18:12

Tarod


You can try to create new QQmlEngine

like image 44
Vladislav Mikitich Avatar answered Dec 09 '25 18:12

Vladislav Mikitich