简体   繁体   中英

Increment QML property of top-level type in child type

I'm new to Qt with QML. I'm trying to set a property at the top element called buttonIndex so that the child elements could change the property by incrementing the value in the Button element to make the name go from "Device 1" -> "Device 15". This is my QML code below:

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
                        }
                    }
                }
            }
        }
    }
}

The output I'm getting is unwanted. I get "Device 107", "Device 108", "Device 109" etc.. I need to have it go from 1-15. I tried using the signal itemAdded in the code and re-assigning the value of the buttonIndex to increment by 1 each time but that didn't work either. And also I need to store that buttonIndex for the Button type such like "item_device_button_1". Any ideas how this can be solved?

As @folibis mentioned, you don't need to create your own property for this. Repeaters (and ListViews, etc.) give delegates access a property called index that already does exactly what you want. The index is 0-based, so if you want it to start at '1', then just add +1.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM