Reputation: 16705
Suppose I have a few items with same behavior:
onActiveFocusChanged: {
this.state = activeFocus ? "shown" : "hidden"
}
states: [
State {
name: "shown"
PropertyChanges {
target: myServersLV
height: 27 * 3
opacity: 1
}
},
State {
name: "hidden"
PropertyChanges {
target: myServersLV
height: 0
opacity: 0
}
}
]
Behavior on opacity {
NumberAnimation { duration: 250
easing {
type: Easing.OutElastic
amplitude: 0.5
period: 2.5
}
}
}
Behavior on height {
NumberAnimation { duration: 250
easing {
type: Easing.OutElastic
amplitude: 0.5
period: 2.5
}
}
}
In these few items the only thing that changes is target
of states and animations. Is it possible to move it in one parent(super) item as like a base class in C++ and inherit this slots, behaviors, etc in QML?
Upvotes: 4
Views: 10940
Reputation: 1728
Here is the MyRectangle.qml
file:
import QtQuick 2.0
Rectangle {
id: rectangle
onActiveFocusChanged: {
this.state = activeFocus ? "shown" : "hidden"
}
states: [
State {
name: "shown"
PropertyChanges {
target: rectangle
height: 27 * 3
opacity: 1
}
},
State {
name: "hidden"
PropertyChanges {
target: rectangle
height: 0
opacity: 0
}
}
]
Behavior on opacity {
NumberAnimation { duration: 250
easing {
type: Easing.OutElastic
amplitude: 0.5
period: 2.5
}
}
}
Behavior on height {
NumberAnimation { duration: 250
easing {
type: Easing.OutElastic
amplitude: 0.5
period: 2.5
}
}
}
}
You can use it like this in every other file in project:
MyRectangle {
color: "red"
width: 200
height: 200
}
When focus
changes on MyRectangle
it is animated properly.
Upvotes: 4
Reputation: 8242
Yes, absolutely. The Qt docs include an example of how to create a reusable Button component. Copying from the docs, here's their Button:
//contents of Button.qml
import QtQuick 1.0
Rectangle {
id: button
width: 145; height: 60
color: "blue"
smooth: true; radius: 9
property alias text: label.text
border {color: "#B9C5D0"; width: 1}
gradient: Gradient {
GradientStop {color: "#CFF7FF"; position: 0.0}
GradientStop {color: "#99C0E5"; position: 0.57}
GradientStop {color: "#719FCB"; position: 0.9}
}
Text {
id: label
anchors.centerIn: parent
text: "Click Me!"
font.pointSize: 12
color: "blue"
}
MouseArea {
anchors.fill: parent
onClicked: console.log(text + " clicked")
}
}
To use this from another file, you reference it based on the filename without the .qml suffix. So a minimal example would be:
Button {}
But you want to set the text, right? All you need to do is this:
Button {
text: "My button text"
}
Why? Because they included an alias property that lets you directly modify the variable of a sub component:
property alias text: label.text
Upvotes: 10