QML与Repeater之间的信号

Signal between QML with Repeater

我有以下 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 access dynamically/randomly loaded Repeater items in QML?

没有成功。 那么,该怎么做呢?

谢谢

你有多种选择。首先是定义绑定,在为委托创建 Component 时:

Repeater {
    id: _windows
    model: instances
    TestWindow {
        index: model.index
        leftOffset: _component.width
        onMySignalToMainWindow: testConnection() <--- Here you can connect it.
    }
}

另一种选择是使用 onItemAddedonItemRemoved-Handlers 并在函数被销毁时连接那里的函数 (mySignalToMainWindow.connect(functionToConnect)) 和相应的 disconnect

如果您希望永久连接,我推荐前者;如果您可能想在某个时候断开连接,我推荐后者。

如果您不为 Repeater 声明 delegate,则 onItemAdded/onRemoved 处理程序尤为重要。例如,如果您使用 DelegateModelObjectModel,就会发生这种情况。对于那些模型,你不能确定,当Repeater添加或删除它们时对象被实例化或销毁,你不能使用经常提到的:Component.onCompleted/onDestruction,所以我认为itemAdded/Removed-信号 superior/more 一般用于 Repeater.