我在某些时候感到困惑,QML
因为我是新手。简化的 QML 代码定义了一个包含一个 ListView 的窗口,其中包含我的委托项目。一键加载和卸载此 ListView 元素。当我加载和卸载 ListView 元素时,我在 TextInput 中编写的所有文本都会按照我的预期从 listModel 中重置。所以我需要动态更新 listModel,这样我就不会丢失我在 TextInput 中写的文本。我在 TextInput 中添加了 Keys.onPressed 来实现这一点。但它适用于一些逻辑错误。当我输入时,假设“aaaa”,然后我卸载 ListView 并通过 Button 再次加载,我得到的是“aaa”(最后一个字母没有传递给 listModel)。这是可以理解的,但在此示例中如何动态更新列表模型角色?
main.qml
ApplicationWindow {
id: applicationWindow
width: 300
height: 200
visible: true
title: qsTr("01_Change_Model_Data")
ListModel {
id: listModel1
ListElement {labelText: "Text Field 1:"; textInput_text : "This is text 1"}
ListElement {labelText: "Text Field 2:"; textInput_text : "This is text 2"}
}
Button {
id: loadUnloadBtn
height: 24
width: 50
text: "Load"
anchors {
right: parent.right
rightMargin: 20
top: parent.top
topMargin: 10
}
onClicked: {
if(listAreaLoader.source == "") {
listAreaLoader.source = "ListArea.qml"
}else {
listAreaLoader.source = ""
}
}
}
Loader {
id: listAreaLoader
anchors {
top: parent.top
topMargin: 10
bottom: parent.bottom
bottomMargin: 10
left: parent.left
leftMargin: 10
right: parent.right
rightMargin: 80
}
source: ""
}
}
ListArea.qml:
Item {
id: listViewDelegate
ListView {
id: listView1
anchors.fill: parent
model: listModel1
delegate: listElementDelegate
spacing: 6
}
Component {
id: listElementDelegate
Rectangle {
color: "#00000000"
height: 24
width: 50
Label {
id: label1
text: labelText
}
Rectangle {
color: "grey"
radius: 4
width: 100
height: 20
anchors {
verticalCenter: label1.verticalCenter
left: label1.right
leftMargin: 10
}
TextInput {
id: textInput1
anchors.fill: parent
leftPadding: 5
rightPadding: 5
clip: true
verticalAlignment: Text.AlignVCenter
text: textInput_text
Keys.onPressed: {
listView1.currentIndex = index
listModel1.setProperty(index, "textInput_text", textInput1.text)
}
}
}
}
}
}