ListView模型函数

ListView model function

我刚刚开始使用 Qt,并尝试创建操作 ListView 模型元素的函数。

我在 "myButton.qml" 中有自定义按钮,它具有 "normal"、"pressed"、"selected" 等状态

ListView 在 "main.qml"。结构是这样的:

ListView{
    //...

    model: nameModel

    delegate: myButton {
        //...
    }

}

所以这是我的目标:这个按钮列表应该像一组单选按钮一样 - 只有一个可以有选择状态,选择状态是当你按下按钮时。我认为我应该有点击处理程序和一个调用按钮点击的函数。函数应检查按钮列表,如果在函数将其状态更改为 "Normal".

之前选择了一个按钮

所以我不知道这个函数应该怎么写,应该放在哪里。我阅读了 Qt 文档,但仍然不知道。

解决此问题的一种可能的简单方法是利用 ExclusiveGroup. As discussed in the documentation,可以将对此类型的支持添加到 any 类型:

It is possible to add support for ExclusiveGroup for an object or control. It should have a checked property, and either a checkedChanged, toggled(), or toggled(bool) signal. It also needs to be bound with ExclusiveGroup::bindCheckable() when its ExclusiveGroup typed property is set.

您可以在 ListView 级别定义一个 ExclusiveGroup 并在 ListView 委托中实现所需的逻辑。通过将委托 ExclusiveGroup 属性 绑定到 ListViewExclusiveGroup 你应该实现你想要的,而不需要爬取模型的函数。

演示用法的最终玩具示例:

import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Controls 1.4


Window {
    id: root
    visible: true
    width: 200
    height: 500

    ListView {
        anchors.fill: parent
        model: 10
        spacing: 20
        ExclusiveGroup { id: ex }   // the group for all the delegate

        delegate: Rectangle {
            id: delegate
            width: ListView.view.width
            height: 30
            color: checked ? "yellow" : "steelblue"

            // code to have exclusive behaviour
            property bool checked: false
            property ExclusiveGroup exclusiveGroup: ex

            onExclusiveGroupChanged: {
                if (exclusiveGroup)
                    exclusiveGroup.bindCheckable(delegate)
            }

            // mouse area to trigger the property change
            MouseArea {
                anchors.fill: parent
                onClicked: checked = true
            }
        }
    }
}