本文介绍了从 Delegate 访问 Listview currentIndex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 QML ListView,其中委托从另一个文件加载它的组件.单击委托项时,我想更新 ListView.CurrentIndexhighlight 所选项目.

I have a QML ListView where the delegate loads it's component from another file. When clicking on an delegate item, I want to update ListView. CurrentIndex and highlight the selected item.

当我显式设置 ListViewid 时,它有效.但是,由于我想对其他 ListView 也使用委托的 Component,我正在努力寻找一种通用的方法来访问 ListView.currentIndex 来自委托Component.

It works, when I explicitly set the id of the ListView. However since I want to use the delegate's Component also for other ListViews, I'm stuggeling to find a generic way how to access ListView.currentIndex from within a delegate Component.

代码如下:

ma​​in.qml

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2

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

    ListModel {
        id: contactsModel
        ListElement {
            name: "Bill Smith"
        }
        ListElement {
            name: "John Brown"
        }
        ListElement {
            name: "Sam Wise"
        }
    }

    ListView{
        id: contactsView
        anchors.left: parent.left
        anchors.top: parent.top
        width: parent.width
        height: parent.height
        orientation: Qt.Vertical
        spacing: 10
        model: contactsModel
        delegate: Contact{}
    }
}

Contact.qml(委托使用的组件)

import QtQuick 2.0

Component{
    id: contact
    Rectangle{
        width: 200
        height: 50
        color: ListView.isCurrentItem ? "#003366" : "#585858"
        border.color: "gray"
        border.width: 1

        MouseArea{
            anchors.fill: parent
            onClicked: {
                ListView.currentIndex = index; // <---- does not work
                //  contactsView.currentIndex = index; // <---- Works
            }
        }

        Text{
            anchors.centerIn: parent
            color: "white"
            text: name
        }
    }
}

非常感谢任何帮助!

推荐答案

这里有两个问题:

  • You need to qualify ListView's attached properties with the name of the item from which they're accessed.
  • The currentIndex property is a property of the ListView item type, not the attached property object.

要同时修复它们,请先更改:

To fix them both, first change this:

ListView.currentIndex = index;

为此:

delegate.ListView.view.currentIndex = index;

然后给你的代表一个id:

Component {
    id: contact

    Rectangle {
        id: delegate
    // ...
}

示例用法证明了这一点(部分)文档部分:

This is demonstrated (in part) by the Example Usage section of the documentation:

ListView 将许多属性附加到委托的根项目,例如 ListView:isCurrentItem.在以下示例中,根委托项可以直接作为 ListView.isCurrentItem 访问此附加属性,而子 contactInfo 对象必须将此属性引用为 wrapper.ListView.isCurrentItem.

这篇关于从 Delegate 访问 Listview currentIndex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:28