首页 > 解决方案 > QML:如何从列表视图中选择单选按钮?

问题描述

我有下一个列表视图组件:

CustomListRadio.qml

import QtQuick 2.12
import QtQuick.Controls 2.12
import "."

Rectangle {
    id: radio_content
    x: 0
    y: 40
    width: 320
    height: 158
    color: "black"

    property int counter: 0
    property int savedIndex: 0
    property int checkedIndex: 0
    property variant internalModel

    ButtonGroup {
        id: buttonGroup
    }

    ListView {
        id: list
        x: 0
        y: 0
        width: 320
        height: 158
        model: parent.internalModel
        anchors.fill: radio_content

        delegate: RadioDelegate {

            text: modelData
            checked: index == radio_content.savedIndex
            ButtonGroup.group: buttonGroup

            font.pixelSize: 23
            font.family: "Futura Condensed"
            font.styleName: "Medium"

            MouseArea {
                anchors.fill: parent
                onClicked: {
                    parent.checked = true
                    radio_content.checkedIndex = model.index
                }
            }

        }
    }
}

RadioDelegate.qml

import QtQuick 2.12
import QtQuick.Controls 2.12

RadioDelegate {
    id: control
    text: qsTr("RadioDelegate")
    checked: true

    contentItem: Text {
        leftPadding: control.indicator.width + control.spacing
        text: control.text
        font: control.font
        opacity: enabled ? 1.0 : 0.3
        color: "white"
        elide: Text.ElideRight
        verticalAlignment: Text.AlignVCenter
    }

    indicator: Rectangle {
        implicitWidth: 30
        implicitHeight: 30
        x: control.leftPadding
        y: parent.height / 2 - height / 2
        radius: 15
        color: control.checked ? "#0088FF" : "white"
        border.color: "#0088FF"

        Rectangle {
            width: 10
            height: 10
            x: parent.width / 2 - width / 2
            y: parent.height / 2 - height / 2
            radius: 5
            color: "white"
            visible: control.checked
        }
    }

    background: Rectangle {
        implicitWidth: 320
        implicitHeight: 40
        color: "black"

        border {
            color: "#383838"
            width: 1
        }

    }
}

如何添加组件

CustomListRadio {
    id: radio_list
    internalModel: msg.languageVariantList
    savedIndex: msg.language
}

它创建一个单选按钮列表。它运作良好。但是,我不能选择默认选中的单选按钮。用鼠标选择开关,有效。但是从代码中,我的解决方案充其量只有在列表的长度等于可见元素的数量时才选择开关。

标签: qtlistviewqml

解决方案


RadioDelegate.qml中的问题,需要删除下一个字符串:

checked: true

推荐阅读