[英]QML inheritance
假設我有一些具有相同行為的項目:
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
}
}
}
在這幾個項目中,唯一改變的是狀態和動畫的target
。 是否可以像在C ++中的基類一樣在一個父(超級)項中移動它並在QML中繼承此插槽,行為等?
是的,一點沒錯。 Qt文檔包含如何創建可重用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")
}
}
要從另一個文件中使用它,請根據不帶.qml后綴的文件名引用它。 所以最小的例子是:
Button {}
但你想設置文本,對吧? 你需要做的就是:
Button {
text: "My button text"
}
為什么? 因為它們包含一個別名屬性,可以直接修改子組件的變量:
property alias text: label.text
這是MyRectangle.qml
文件:
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
}
}
}
}
您可以在項目中的每個其他文件中使用它:
MyRectangle {
color: "red"
width: 200
height: 200
}
當focus
在MyRectangle
發生變化時,它會被正確地設置動畫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.