如何避免QML中的重复代码?

时间:2015-03-06 22:52:31

标签: qt qml generalization

我正在使用Qt 5.4.1。

我目前正在QML中设置一些按钮。我想要一些按钮的类似状态行为 - 如何避免通过QML重复大块非常相似的代码?

Rectangle {
        id: songFilterButton

        x: 0; width: 80
        y: 0; height: 60

        Text {
            anchors.centerIn: parent
            text: "Songs"
        }

        state: "on"; states: [
            State {
                name: "on"
                PropertyChanges{ target: songFilterButton; color: "steelblue" }
            },
            State {
                name: "on"
                PropertyChanges{ target: songFilterButton; color: "white" }
            }
        ]

        MouseArea { id: region; anchors.fill: parent; onClicked: songFilterButton.toggle() }

        function toggle() {
            if(state == "on") { state = "off" } else { state = "on" }
        }
    }

对于几个按钮重复这个代码是相当多的,每次我添加一个按钮功能(比如向C ++和其他行为发送信号),我将不得不多次执行...

我已阅读MrEricSir提供的链接,并使用以下代码创建了HKRadioButton.qml:

import QtQuick 2.0

Rectangle {
    property string text: label.text

    Text {
        id: label
        anchors.centerIn: parent
    }

    state: "on"; states: [
        State {
            name: "on"
            PropertyChanges{ target: songFilterButton; color: "steelblue" }
        },
        State {
            name: "off"
            PropertyChanges{ target: songFilterButton; color: "white" }
        }
    ]

    MouseArea { anchors.fill: parent; onClicked: parent.toggle() }

    function toggle() {
        if(state == "on") { state = "off" } else { state = "on" }
    }
}

在我的主要QML文件中,我有

HKRadioButton {
        id: songFilterButton

        x: 0; width: 80
        y: 0; height: 60

        text: "Songs"
    }

我得到的行为(改变状态),但不是文本......

2 个答案:

答案 0 :(得分:2)

更改

property string text: label.text

property alias text: label.text

现在您只需将labeltext分配给自己的财产HKRadioButtontext,但这应该是相反的行动。

答案 1 :(得分:2)

定义您自己的组件。您可以“就地”创建组件,然后右键单击组件的根对象 - >重构 - >将组件移动到单独的文件中例如:

Rectangle {
    id: button
    ...
}

将其移至Button.qml后,您只需使用:

Button {
    ...
}

使用“内联”组件:

Component {
    id: button
    Rectangle {
        ...
    }
}

然后,您可以button使用Loader或使用button.createObject(parentItem)进行动态实例化

正如另一个答案所指出的,如果要为组件创建引用某些子对象属性的属性,请使用别名属性,以帮助避免不必要的绑定。

Rectangle {
    property string text

    Text {
        id: label
        anchors.centerIn: parent
        text: parent.text // this is what you want
    }
    ...
}

但是这会引入一个不必要的绑定,您可以使用alias直接从根组件属性引用标签的text作为folibis建议。

相关问题