Qtquick qml : How to seperate Logic from UI in Qtquick UI Application?
-
I am using Qt quick UI Forms.
I want to seperate Logic code from UI code as myApp.qml and myAppForm.ui.qml.
ui.qml does not support javascript logic, for example, mouse events.
Now, the following problem.
//myAppForm.ui.qml import QtQuick 2.4 Item { Rectangle { id: rectangle1 color: "#a0ebfb" anchors.fill: parent MouseArea { id: mouse1 anchors.fill: parent } } }
The above is the UI code. I need to separate the logic code as,
//myApp.qml import QtQuick 2.4 myAppForm { mouse1{ onClicked: { rectangle1.color = 'red' } } }
Obviously, the above does not work. I am asking how to do something similar.
Thanks. -
ui.qml does not support javascript logic, for example, mouse events.
That's not true.
To separate logic part you can try following 2 ways:
- Create a separate javascript file and import it in your QML. This js contains all your logic.
- Create a separate QML component in which individual components have their own logic. Then access this component in your other QML files by its name.
-
I have solved this problem.
The Documentation section is here : http://doc.qt.io/qtcreator/creator-quick-ui-forms.htmlTo access any object outside the .qml file or ui.qml file in which it is defined in it has to be "exported" like in many other languages.
All qml files are accessible from other qml files. "Item" qml type properties are accessible by default. Other types and properties must be alias-ed to make it accessible.
One can also use the "Connection" qml type to add signals and handlers. See the documentation here : http://doc.qt.io/qt-5/qtqml-syntax-signals.html
Qt has excellent documentation but alas one must persevere through them. Qt 5.7 qml videos are rare.
I wish someone could make qt 5.7 qml videos in the near future.Thanks.
Here's how the above code works.
//myAppForm.ui.qml Item { Property alias rectMouseArea: mouse1 Rectangle { id: rectangle1 color: "#a0ebfb" anchors.fill: parent MouseArea { id: mouse1 anchors.fill: parent } } }
//myApp.qml import QtQuick 2.4 myAppForm { //mouse1{ rectMouseArea.onClicked: { rectangle1.color = 'red' } //} }