QML 如何通过单击 listView 委托中定义的复选框来获取 ListView 中的索引号?

QML how to get index number in a ListView by clicking a checkbox defined inside a delegate of a listView?

  1. 好吧,我正在尝试在 listView 中创建一个包含两个文本和一个复选框的项目列表。
  2. 我想在选中复选框时添加商品的价格。
  3. 为此,我需要知道 listView 项目的索引,以便我可以获取 它 "price" 我可以存储数据。
  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
            }
    }

您可以使用 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 : ""
                }
            }
    }