Reputation: 194
I'm using QQmlApplicationEngine
то load my main window.
QQmlApplicationEngine engine;
engine.load("GUI.qml");
Where GUI.qml
is my main GUI file. How I can create and destruct a new window from code? As far as I can see, if I write engine.load("SecondWindow.qml");
, how I can close it? Or I should create and destruct such objects from QML itself?
Upvotes: 0
Views: 284
Reputation: 1293
Option 1: You can do it from QML, see this sample:
import QtQuick 2.12
import QtQuick.Controls 2.5
ApplicationWindow {
id: window
visible: true
width: 640
height: 480
title: "Window 1"
CheckBox {
id: cb
text: "Show Window #2"
}
Loader {
active: cb.checked
sourceComponent: Component {
ApplicationWindow { // Or "SecondWindow"
visible: true
width: 640
height: 480
title: "Window 2"
}
}
}
}
Option 2: Also, you can control it from C++ side, for example like this:
QML
import QtQuick 2.12
import QtQuick.Controls 2.5
ApplicationWindow {
id: window
visible: true
width: 640
height: 480
title: "Window 1"
Loader {
active: showWindowFlag
// Instead of "sourceComponent" you can use
// source: "SecondWindow.qml"
sourceComponent: Component {
ApplicationWindow {
visible: true
width: 640
height: 480
title: "Window 2"
}
}
}
}
C++
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QTimer>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
bool showWindowFlag = false;
engine.rootContext()->setContextProperty("showWindowFlag", showWindowFlag); // !!!!
auto timer = new QTimer(&engine); // Parent will delete timer
QObject::connect(timer, &QTimer::timeout, [&](){
showWindowFlag = !showWindowFlag;
engine.rootContext()->setContextProperty("showWindowFlag", showWindowFlag);
});
timer->setInterval(1000);
timer->setSingleShot(false);
timer->start();
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
Upvotes: 1