QML: How to get proper child windows
-
Hi there,
since I struggled a lot with producing a proper parent - child relation for different dialogs and subdialogs, I want to distribute my experience in case someone is facing the same problem:
Lets assume we want to have one main window and different subdialogs, when a user presses a button/menu button. For the sake of simplicity, we create only a dummy window:
@
import QtQuick 2.1
import QtQuick.Window 2.1Window {
id: mainWindow
title: "My MainWindow"
width: 640
height: 480
visible: true
}
@Lets assume, you want to have a child window, e.g. let the user change some settings or whatever. You are creating another Window {} nested into the main one:
@
Window {
id: mainWindow
title: "My MainWindow"
width: 640
height: 480
visible: trueWindow {
id: childWindow
title: "My ChildWindow"
width: 640
height: 480
visible: true
}
}
@Try this example and you probably will wonder, why you have two standalone dialogs, especially the child window is not a child.
Why does that happen? The thing is, when the childWindow C++ object is created, the QWindow pointer from mainWindow is passed to the child object by the method QWindow::setTransientParent(). When the native window for the child is created using the platform code, there is a check if a parent exist. Unfortunately, the pointer to the parent is NULL because the parent QWindow object is not created completely (I'm not sure how QML objects are created, but maybe the child objects are created before the parent objects are complete). So guess what happens? The child window has no parent and acts as a parentless window.
Whats the workarround? If you need a child window like in this case. Don't set visible: true. Set it to visible later in C++ or by emitting a signal.
One possible way of doing this is:@
import QtQuick 2.1
import QtQuick.Window 2.1
import QtQuick.Controls 1.0Window {
id: mainWindow
title: "My MainWindow"
width: 640
height: 480
visible: trueButton {
text: "Click me"
onClicked: childWindow.visible = !childWindow.visible
}Window {
id: childWindow
title: "My ChildWindow"
width: 640
height: 480
}
}
@If you click the button, a child window is opened and yes... its now a proper child :)
At the experts: would you please tell me, if I should raise a bug report or is this behavior intended?