【发布时间】:2016-09-07 20:26:39
【问题描述】:
我有一个动态添加项目的 ListView,我有点想知道如何通过索引访问项目。具体来说,我希望在使用颜色对话框更改颜色时更改项目矩形的颜色。我猜应该可以在调用颜色对话框之前先为当前项目设置一个变量,然后在 onAccepted 方法中使用该变量更改该项目的颜色,但我不知道如何实现这一点QML,因为我对 QML 比较陌生。当颜色对话框关闭时(onAccepted),也许您可以提供一种更简洁的方法来更改项目矩形的颜色。感谢您的帮助! :)
import QtQuick 2.0
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtQuick.Dialogs 1.2
import QtQuick.Controls.Styles 1.4
Rectangle {
id: listViewContainer
width: parent.width/10*9;
height: 50
Behavior on height {
NumberAnimation {
duration: 100;
}
}
gradient: Gradient {
GradientStop {position: 0.0; color: "white" }
GradientStop {position: 1.0; color: "silver" }
}
radius: 5
ColorDialog {
id: colorDialog
title: "Please choose a color"
onAccepted: {
console.log("You chose: " + colorDialog.color)
Qt.quit()
}
onRejected: {
console.log("Canceled")
Qt.quit()
}
}
Component {
id: playerDelegate
Item {
anchors.left: parent.left
anchors.right: parent.right
height: 50
Column {
Text { text: '<b>Name:</b> ' + name }
Row {
MouseArea {
width: 20
height: 20
onClicked: {
colorDialog.visible = true;
playerColor = colorDialog.color;
//open color dialog
}
Rectangle {
radius: 3
anchors.fill: parent
color: playerColor
}
}
}
}
}
}
ListView {
id: playerListView
anchors.fill: parent
model:
ListModel {
id: playerListViewModel;
ListElement {
name: "Bill Smith"
playerColor: "red"
}
}
delegate: playerDelegate
}
Button {
id: addPlayerButton
anchors.top: playerListView.bottom
anchors.left: playerListView.left
anchors.right: playerListView.right
style: ButtonStyle {
label: Text {
text: "Add new player"
horizontalAlignment: Text.Center
}
}
onClicked: {
root.addnewPlayer(playerListView); //dont worry about this method
playerListViewModel.append({name: "Billy", playerColor: "blue"});
listViewContainer.height += 50;
}
}
}
【问题讨论】:
-
运行您的示例时出现错误:
file:///tmp/untitled3/main.qml:9: TypeError: Cannot read property of null请发布一个完整的最小示例。我猜这段代码是从一段更大的代码中取出来的,因此它所指的父级是窗口?