我有以下qml文件,main.qml创建TestWindow.qml元素 .
我想将TestWindow.qml中的信号(单击按钮mySignalToMainWindow())连接到main.qml,testConnection()中的函数 .
main.qml
Window {
id: _component
property int instances: 3
width: 200
height: Screen.height / 2
visible: true
Component.onCompleted: {
x = 40
y = 40
}
Repeater {
id: _windows
model: instances
TestWindow {
index: model.index
leftOffset: _component.width
}
}
Column {
Repeater {
model: instances
Button {
text: "Window " + index
onClicked:{ _windows.itemAt(index).window.raise();
}
}
}
}
function testConnection(){console.log("Subwindow To Main Window")}
}
和TestWindow.qml:
Item {
id: _windowItem
property int index
property int leftOffset
property alias window: _window
signal mySignalToMainWindow()
Window {
id: _window
visible: true
title: "SubWindowText " + index
Component.onCompleted: {
x = leftOffset
y = 40
width = Screen.width - leftOffset
height = Screen.height / 2
}
Text {
id: windowText
text: qsTr("SubWindowText")
}
Button {
text: "SubWindow " + index
onClicked: {console.log("TestWindow::Button onClicked "+_window);
_windowItem.mySignalToMainWindow();
}
}
}
}
我测试了这两个:
How to bind to a signal from a delegate component within a ListView in QML和How to access dynamically/randomly loaded Repeater items in QML?
没有成功 . 那么,该怎么做?
谢谢
1 回答
你有多种选择 . 第一种是在为委托创建
Component
时定义绑定:另一个选择是使用
onItemAdded
和onItemRemoved
-Handlers并将其中的函数(mySignalToMainWindow.connect(functionToConnect)
)和相应的disconnect
连接起来 .如果您希望连接是永久性的,我建议使用前者,如果您希望在某个时间断开连接,我建议使用后者 .
如果您没有为
Repeater
声明delegate
,则onItemAdded/onRemoved
处理程序尤为重要 . 例如,如果您使用DelegateModel
或ObjectModel
,就会发生这种情况 . 与那些模型一样,你不能确定,当Repeater
添加或删除它们时,对象被实例化或销毁,你不能使用经常提到的:Component.onCompleted/onDestruction
,所以我认为itemAdded/Removed
-signals优越/更通用的使用用Repeater
.