首页 > 解决方案 > QML以编程方式将ListView中的ExclusiveGroup设置为RadioButton

问题描述

再会

我正在尝试创建一个包含 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);
}

如果我添加部分 eg:eg1ListElement那么它会给出一个错误

ListElement: cannot use script for property value

标签: qtqmlqt5

解决方案


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

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

推荐阅读