I am really new to QML and I am struggling with defining a basic layout in QML. How do you anchor an element to the window, so that is resizes when the window is resized by the user? I want to add a Rectangle that fills all space available in the window, but I haven't found a way to do this from inside the qml file. All examples I have found so far use a fix width and height, but this means that the element will keep its preset size when the size of the window changes.
2 Answers
For your specific problem :
- Anchor all the elements based on their parents(siblings).
- Always make your top qml elemnt to fill the viewer space as explained here.
Adding to it. Whenever you need such kind of re sizing to be done, you need to inform from one side to the other about change in geometry. By sides I mean, from qml to C++ or from C++ to qml.
To tell qml about resizing in the top window :
Your top parent element in qml will not get any signal about resizing of the widget. You need to do it manually.
To get the information that top widget has actually re sized, you need to implement the resizeEvent function.
Whenever your implementation gets called, you need to signal the qml side that some resizing has happened and thus the top qml parent should also resize itself.
To tell C++ about resizing in the top qml element :
Similarly, your widget in C++ will not get any signal about resizing of the top qml element. You need to do it manually:
- Expose a class from C++ side to qml.
- Whenever top qml element changes, call a function of this class to inform this change, and ask it to resize the top widget as well.
The simple answer to this is to use
Item {
anchors.fill: parent
}
which is equivelent to
Item {
anchors {
top: parent.top
left: parent.left
right: parent.right
bottom: parent.bottom
}
}
where parent is the object you want the item to be anchored inside. While this is usually the parent it can technically be anchored to anything.
I want to add that usually you statically size your top level element, since with the default options in a qml application, the application window will size to the size of the root element in your main qml file. If you want to do something trickier, you will need to modify the C++ that generates the QDeclarativeView for your application.