Reputation: 7188
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?
Upvotes: 3
Views: 5035
Reputation: 7188
For anyone curious, I ended up solving the problem with slightly different approach.
My root QML document now looks like this:
import QtQuick 2.4
Item {
MyMainWindow {
visible: true
}
MyAuxiliaryWindow {
visible: true
}
}
Where MainWindow
is a QML component with root element ApplicationWindow
and AuxiliaryWindow
is a component with root element Window
.
Works just fine and you don't have to worry about loading two separate QML files.
Upvotes: 0
Reputation: 7170
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();
Upvotes: 6