【问题标题】:Is there a way to grab the index of an item in Listview?有没有办法在 Listview 中获取项目的索引?
【发布时间】:2020-11-18 01:57:59
【问题描述】:

我在 Qt/qml 中使用 listview 并试图显示一个屏幕,将字体 A 提供给列表中的第一个文本,然后将字体 B 提供给第二个文本,然后是 A,然后是 B,依此类推......

我一直在尝试在字体属性中使用条件来实现 字体:(索引%2)字体A:字体B

我无法准确地获取每个索引,如果有任何建议或指导,我将不胜感激,谢谢!

【问题讨论】:

  • 据我所知,没有。我正在尝试使用组件内部的索引,没有 x,y 坐标,也不需要选择项目。不过,我很感谢您的参考。
  • 我认为您的问题将从添加您现在拥有的代码中受益。可以添加相关的sn-p吗?

标签: qt qml


【解决方案1】:

您可以为此使用 index 属性。无论它是组件还是直接子代,它都将在您的委托中可用。检查以下sn-p:

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ListView {
        id: listView
        anchors.fill: parent
        model: 5

        delegate: Rectangle {
            width: listView.width
            height: listView.height / listView.count

            color: index === 1 ? "red" : "blue"
        }
    }
}

index 将保存您的项目的索引,从 0 开始。因此在本例中,第二个项目将被涂成红色。

同样适用于组件:

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    ListView {
        id: listView
        anchors.fill: parent
        model: 5

        delegate: comp
        
        Component {
            id: comp
            
            Rectangle {
                width: listView.width
                height: listView.height / listView.count
    
                color: index === 1 ? "red" : "blue"
            }
        }
    }
}

【讨论】:

  • 我的代码采用了另一种方式,但我现在可能会更改它以使用它。我遇到的问题是我正在编辑的领域不是我委派的领域的孩子。无论如何,谢谢!
  • 我建议您始终使用“model.index”而不仅仅是“index”。如果您使用真实模型的角色而不仅仅是索引,则可以更清楚地了解值的来源并避免冲突。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-01
  • 2012-05-31
相关资源
最近更新 更多