我一直在尝试对话框,有一些东西困扰着我。
我有以下代码:
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Button {
id: click
x: 285
y: 189
text: qsTr("Click")
onClicked: dlgTest.open()
}
Dialog{
id:dlgTest
visible:false
contentItem: Rectangle{
width: 300
height: 300
TextField{
id: tfText
anchors.top: parent.top
}
Button{
anchors.top: tfText.bottom
onClicked: dlgTest.close()
text: "Close"
}
}
}
}
当我第一次打开它时,我向TextField添加了一些文本,然后我关闭了它。但是,如果我再次打开它,文本仍然在那里。我想要的是"重置"对话框到它的原始状态,当我打开它的第一次(与一个空的TextField)。似乎调用方法"close"与将visible改为false完全相同。
是否有一种方法来做这个"重置"?
我有一个有很多控件的对话框,手动恢复所有的东西很烦人。
在您的代码中,您只创建一次对话框,作为ApplicationWindow
的子对话框。要"重置"它,您有两个选项:
- 有一个重置功能,你调用,并恢复一切。你也可以用这个在第一时间设置
- 创建一个新的对象,所有的东西都设置到位。
对于后者,您可以使用JavaScript动态对象创建或Loader
。
Button {
id: click
x: 285
y: 189
text: qsTr("Click")
onClicked: {
var d = diaComp.createObject(null)
d.open()
}
}
Component {
id: diaComp
Dialog{
id:dlgTest
visible:false
contentItem: Rectangle{
width: 300
height: 300
TextField{
id: tfText
anchors.top: parent.top
}
Button{
anchors.top: tfText.bottom
onClicked: {
dlgTest.close()
dlgTest.destroy()
}
text: "Close"
}
}
}
}
然而,当您销毁对象时,属性的内容将丢失,并且您无法再访问它们。所以你需要确保,首先将它们复制(而不是绑定)到一些没有被销毁的属性上。
与Loader
你有可能卸载对话框之前,你再次加载它,这基本上重置它。但是,在您卸载它之前,您仍然可以访问它的值,正如您在Button
的onClicked-handler中所看到的那样。
Button {
id: click
x: 285
y: 189
text: qsTr("Click")
onClicked: {
console.log((dlgLoad.status === Loader.Ready ? dlgLoad.item.value : 'was not loaded yet'))
dlgLoad.active = false
dlgLoad.active = true
dlgLoad.item.open()
}
}
Loader {
id: dlgLoad
sourceComponent: diaComp
active: false
}
Component {
id: diaComp
Dialog{
id:dlgTest
visible:false
property alias value: tfText.text
contentItem: Rectangle{
width: 300
height: 300
TextField{
id: tfText
anchors.top: parent.top
}
Button{
anchors.top: tfText.bottom
onClicked: {
dlgTest.close()
}
text: "Close"
}
}
}
}
当然,您也可以从Loader的项目中复制的值,然后更早地卸载它,以释放内存。
但是如果Dialog
经常(大多数时候)显示,那么通过重用它并手动重置它来避免对象的创建和销毁可能是最明智的。