gpt4 book ai didi

qt - 如何在 QML 中访问和更改组件中的项目

转载 作者:行者123 更新时间:2023-12-04 16:30:42 24 4
gpt4 key购买 nike

在一个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
}
}

我想通过 JS 函数(在同一文件中)更改 TextField 的文本,例如:

function updatedetail(clear,rowindex){
if(clear){
textField_id.text="";
}
else{
textField_id.text=jsonModel1.model.get(rowindex).id;
}
}

但是有一个错误:

ReferenceError: textField_id is not defined

哪里出错了?

最佳答案

当您尝试更改尚未实例化的对象时,它将失败。但即使它被实例化,它的 id 也会在不同的范围内,不能那样访问。
这是必要的,因为同一个 Component 可能会被多次实例化(例如,作为 ListView 中的 delegate),所以它在上下文不再。

在实例化您的 StackView 时,您的 Component 将被实例化并推送到 StackView 上。现在您有了一个实例,可以通过使用以下方式更改公开的属性:

currentItem.textFieldText = newValue

在你的函数中。为此,您需要公开该属性:

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("")
}
}
}

但是,由于实例可能会在以后被销毁并重新创建,因此这种更改不会是永久性的,因此最好将 TextField.text 绑定(bind)到一个对象的属性,该属性将继续存在只要有必要。这可以是从 C++ 公开的 contextProperty 或作为模型传递的 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
}
}
}
}

关于qt - 如何在 QML 中访问和更改组件中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44583656/

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