Can't we have two Rectangle objects defined in a single qml file?
-
Hi,
I have a Rectangle object defined in the default qml file that we get when we create a new project.
I wanted another screen to open up on click of mouse. For this I tried to create another Rectangle object
in the same qml file but I got a syntax error.Is it not possible to create two Rectangle objects in a single .qml file or what?
Basically if I have to have multiple screens in my application switching them back and forth, how should I go about it in terms
of qml files? Shall I have one qml file for one screen or how?Please let me know.
Thanks
-
You can only have one top-level item in a QML file, as stated in the "QML document overview":http://qt-project.org/doc/qt-5.0/qtqml/qtqml-documents-topic.html
There are a few approaches you can take to implement multiple in-application screens:
Define as many items as you want and toggle their visibility, simulating page transitions. Top-level item "states":http://qt-project.org/doc/qt-5.0/qtquick/qtquick-statesanimations-states.html might be useful to monitor these. This is the most straightforward solution, but it gets cumbersome with the application complexity growing.
@Item {
id: topLevelItemRectangle { id: firstRectangle visible: true } Rectangle { id: secondRectangle visible: false } MouseArea { onClicked: parent.state = "second" } states: State: { name: "second" PropertyChanges { target: firstRectangle; visiblity: false } PropertyChanges { target: secondRectangle; visibility: true } }
}@
Implement a "StackView":http://doc-snapshot.qt-project.org/qt5-stable/qtquickcontrols/qml-qtquick-controls1-stackview.html . With it, use different QML files for different pages you called screens and change to them by supplying the StackView with their URL.
@Item {
id: topLevelItemStackView { id: stackView initialItem: Qt.resolvedUrl("FirstRect.qml") } MouseArea { onClicked: stackView.push("SecondRect.qml") }
}@
Use a "Loader":http://qt-project.org/doc/qt-5.0/qtquick/qml-qtquick2-loader.html element to load another QML file and change its source to another file when deemed necessary. Example on the documentation page.