QML继承

Vic*_*voy 2 inheritance qt qml

假设我有一些具有相同行为的项目:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在这几个项目中,唯一改变的是target状态和动画.是否可以像在C++中的基类一样在一个父(超级)项中移动它并在QML中继承此插槽,行为等?

MrE*_*Sir 7

是的,一点没错.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")
     }
 }
Run Code Online (Sandbox Code Playgroud)

要从另一个文件中使用它,请根据不带.qml后缀的文件名引用它.所以最小的例子是:

Button {}
Run Code Online (Sandbox Code Playgroud)

但你想设置文本,对吧?你需要做的就是:

Button {
    text: "My button text"
}
Run Code Online (Sandbox Code Playgroud)

为什么?因为它们包含一个别名属性,可以直接修改子组件的变量:

property alias text: label.text
Run Code Online (Sandbox Code Playgroud)