QML以编程方式将ExclusiveGroup设置为ListView中的RadioButton

时间:2018-11-02 14:48:06

标签: qt qml qt5

美好的一天

我正在尝试创建一个包含RadioButton控件的动态列表视图。 我想有4行,每行将包含4个单选按钮,并且每行上的按钮都属于一个ExclusiveGroup

我曾尝试在创建ListElement时直接设置ExclusiveGroup,但它给出了错误

ExclusiveGroup {id: eg1}
ExclusiveGroup {id: eg2}
ExclusiveGroup {id: eg3}

ListView {
    id: listView
    anchors.fill: parent
    model: myModel
    delegate: RowLayout {
        //property ExclusiveGroup eg: null
        spacing: 5
        RadioButton {
            id: r1
            text: option_1
            //exclusiveGroup: eg
        }
        RadioButton {
            id: r2
            text: option_2
            //exclusiveGroup: eg
        }
        RadioButton {
            id: r3
            text: option_3
            //exclusiveGroup: eg
        }
        RadioButton {
            id: r4
            text: option_4
            //exclusiveGroup: eg
        }
    }
}

ListModel {
    id: myModel
    ListElement {option_1: "8"; option_2: "9"; option_3: "37"; option_4: "27"}//; eg: eg1}
    ListElement {option_1: "12"; option_2: "15"; option_3: "16"; option_4: "17"} //; eg: eg2);
    ListElement {option_1: "1936"; option_2: "1938"; option_3: "1939"; option_4: "1940"} //; eg: eg3);
}

如果我在ListElement中添加eg:eg1这部分,则会出现错误

ListElement: cannot use script for property value

1 个答案:

答案 0 :(得分:1)

如果您希望每行中的按钮是互斥的,则可以使其成为委托的一部分:

ListModel {
    id: myModel
    ListElement {option_1: "8"; option_2: "9"; option_3: "37"; option_4: "27"}
    ListElement {option_1: "12"; option_2: "15"; option_3: "16"; option_4: "17"}
    ListElement {option_1: "1936"; option_2: "1938"; option_3: "1939"; option_4: "1940"}
}

ListView {
    id: listView
    anchors.fill: parent
    model: myModel
    delegate: RowLayout {
        ExclusiveGroup { id: group } // <---
        spacing: 5
        RadioButton {
            id: r1
            text: option_1
            exclusiveGroup: group
        }
        RadioButton {
            id: r2
            text: option_2
            exclusiveGroup: group
        }
        RadioButton {
            id: r3
            text: option_3
            exclusiveGroup: group
        }
        RadioButton {
            id: r4
            text: option_4
            exclusiveGroup: group
        }
    }
}