簡體   English   中英

在子類型中增加頂級類型的 QML 屬性

[英]Increment QML property of top-level type in child type

我是 Qt 和 QML 的新手。 我正在嘗試在頂部元素上設置一個名為buttonIndex的屬性,以便子元素可以通過增加 Button 元素中的值來更改屬性,以使名稱 go 從“設備 1”->“設備 15”。 這是我的 QML 代碼如下:

Page {
    id: page_device
    width: 1024
    height: 600

    property int buttonWidth: 170;
    property int buttonHeight: 100;
    property int buttonIndex: 1;

    header: Label {
        id: label_header_devices
        text: qsTr("Devices")
        font.pixelSize: Qt.application.font.pixelSize * 2
        padding: 20
    }

    Item {
        id: item_devices
        width: 300
        height: 200
        anchors.horizontalCenter: parent.horizontalCenter
        anchors.verticalCenter: parent.verticalCenter

        Column {
            anchors.horizontalCenter: parent.horizontalCenter
            anchors.verticalCenter: parent.verticalCenter
            spacing: 10

            Repeater {
                id: item_devices_rows
                model: 3

                Row {
                    spacing: 10

                    Repeater {
                        id: item_devices_columns
                        model: 5

                        Button {
                            id: button_device_
                            width: buttonWidth
                            height: buttonHeight
                            text: qsTr("Device ") + page_device.buttonIndex++
                            Material.foreground: Material.Pink
                            enabled: false
                            hoverEnabled: false
                            
                            // onClicked: Material.background = Material.Teal
                        }
                    }
                }
            }
        }
    }
}

我得到的 output 是不需要的。 我得到“設備 107”、“設備 108”、“設備 109”等。我需要從 1-15 獲得 go。 我嘗試使用代碼中的信號itemAdded並重新分配buttonIndex的值以每次增加 1,但這也不起作用。 而且我還需要為 Button 類型存儲該 buttonIndex,例如“item_device_button_1”。 有什么想法可以解決這個問題嗎?

正如@folibis 提到的,您不需要為此創建自己的財產。 中繼器(和 ListViews 等)使委托可以訪問一個名為index的屬性,該屬性已經完全符合您的要求。 索引是從 0 開始的,所以如果你希望它從 '1' 開始,那么只需添加 +1。

Repeater {
    Button {
        text: qsTr("Device ") + (index + 1)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM