首页 > 解决方案 > QML如何通过单击listView代表内定义的复选框来获取ListView中的索引号?

问题描述

  1. 好吧,我正在尝试在 listView 中创建一个包含两个文本和一个复选框的项目列表。
  2. 我想在选中复选框时添加商品的价格。
  3. 要做到这一点,我需要知道 listView 的项目的索引,以便我可以获得它的“价格”并存储数据。
  4. 我无法通过复选框获取列表的当前索引,因为它表现为单个实体。
  5. 但是,如果我放置鼠标区域,我可以获得索引,但我需要通过复选框来获取它。

以供参考:

Component {     // delegate
        id:_delegate

        Rectangle{
            width: 100
            height: 50
            color: "beige"
            border.color: "black"
            Text {
                id: _textid
                text: name
            }
            Text {
                id: _textid2
                anchors.top: _textid.bottom;anchors.topMargin: 5
                anchors.left: _textid.left
                text: price
            }
            CheckBox {
            id:_checkbox
            anchors.top:parent.top;anchors.topMargin: 5
            anchors.left: parent.left;anchors.leftMargin: 50
            }
    }

标签: qqmlcomponent

解决方案


您可以使用 onCheckedChanged 事件,然后从模型中获取当前索引的价格,如下所示:

Component {     // delegate
        id:_delegate

        Rectangle{
            width: 100
            height: 50
            color: "beige"
            border.color: "black"
            Text {
                id: _textid
                text: name
            }
            Text {
                id: _textid2
                anchors.top: _textid.bottom;anchors.topMargin: 5
                anchors.left: _textid.left
                text: price
            }
            CheckBox {
                id:_checkbox
                anchors.top:parent.top;anchors.topMargin: 5
                anchors.left: parent.left;anchors.leftMargin: 50

                onCheckedChanged: {
                    _textid2.text = _checkbox.checked ? your_model.get(index).price : ""
                }
            }
    }

推荐阅读