【问题标题】:Signal between QML with RepeaterQML 与中继器之间的信号
【发布时间】:2017-02-23 09:22:03
【问题描述】:

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

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

谢谢

【问题讨论】:

    标签: connection qml signals repeater


    【解决方案1】:

    您有多种选择。首先是定义绑定,在为委托创建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-signals 更好/更一般地用于Repeater

    【讨论】: