在 Qml 文件中,代码如下:
StackView {
id: stackView
anchors.right: parent.right
width: parent.width/2-20
initialItem:patientdetail
Component{
id:patientdetail
Column {
id:detailcolumn
spacing: 2
anchors.right: parent.right
width: parent.width/2-20
Label {
id: label
color: "#ffffff"
text: qsTr("User ID")
}
TextField {
id: textField_id
readOnly: true
placeholderText: qsTr("")
}
}
}
Component{
id:component2
//...other component will add to stackview
}
}
Run Code Online (Sandbox Code Playgroud)
我想通过 JS 函数(在同一个文件中)更改 TextField 的文本,例如:
function updatedetail(clear,rowindex){
if(clear){
textField_id.text="";
}
else{
textField_id.text=jsonModel1.model.get(rowindex).id;
}
}
Run Code Online (Sandbox Code Playgroud)
但是有一个错误:
ReferenceError: textField_id 未定义
错误发生在哪里?
当您尝试更改尚未实例化的对象时,它将失败。但即使它被实例化,它id也会在不同的范围内,不能像那样到达。
这是必要的,因为它Component可能会被多次实例化(例如 a delegatein a ListView),因此它在上下文中不再是唯一的。
在您的实例化后StackView,您Component将被实例化并推送到StackView. 现在您有一个实例,并且可以使用以下方法更改公开的属性:
currentItem.textFieldText = newValue
Run Code Online (Sandbox Code Playgroud)
在你的函数中。为此,您需要公开该属性:
Component{
id:patientdetail
Column {
id:detailcolumn
spacing: 2
anchors.right: parent.right
width: parent.width/2-20
property alias textFieldText: textField_id.text // in this context, you have access to the id. Expose it, to change it from the outside.
Label {
id: label
color: "#ffffff"
text: qsTr("User ID")
}
TextField {
id: textField_id
readOnly: true
placeholderText: qsTr("")
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,由于实例可能会在以后被销毁和重新创建,因此这种更改不会是永久性的,因此最好将 绑定TextField.text到对象的属性,该属性将在需要时继续存在。这可能是contextProperty从 C++ 公开的或QtObject作为模型传递的,或者只是一个属性,例如在StackView.
StackView {
id: stackView
anchors.right: parent.right
width: parent.width/2-20
initialItem:patientdetail
// Change this property. The textField_id.text will be bound to it.
property string textFieldText
Component{
id:patientdetail
Column {
id:detailcolumn
spacing: 2
anchors.right: parent.right
width: parent.width/2-20
Label {
id: label
color: "#ffffff"
text: qsTr("User ID")
}
TextField {
id: textField_id
readOnly: true
placeholderText: qsTr("")
text: stackView.textFieldText
}
}
}
}
Run Code Online (Sandbox Code Playgroud)