gpt4 book ai didi

qt - 从委托(delegate)访问 ListView currentIndex

转载 作者:行者123 更新时间:2023-12-01 22:10:17 24 4
gpt4 key购买 nike

我有一个 QML ListView,其中委托(delegate)从另一个文件加载其组件。单击委托(delegate)项目时,我想更新 ListViewCurrentIndex突出显示所选项目。

当我显式设置 ListViewid 时,它起作用了。但是,由于我想将委托(delegate)的 Component 也用于其他 ListView ,所以我很难找到一种访问 ListView.currentIndex 的通用方法> 来自委托(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(委托(delegate)使用的组件)

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
}
}
}

非常感谢任何帮助!

最佳答案

这里有两个问题:

要解决这两个问题,请首先更改此内容:

ListView.currentIndex = index;

对此:

delegate.ListView.view.currentIndex = index;

然后为您的委托(delegate)提供一个 id:

Component {
id: contact

Rectangle {
id: delegate
// ...
}

Example Usage(部分)证明了这一点文档部分:

ListView attaches a number of properties to the root item of the delegate, for example ListView:isCurrentItem. In the following example, the root delegate item can access this attached property directly as ListView.isCurrentItem, while the child contactInfo object must refer to this property as wrapper.ListView.isCurrentItem.

关于qt - 从委托(delegate)访问 ListView currentIndex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31966104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com