首页 文章

QML与Repeater之间的信号

提问于
浏览
1

我有以下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?

没有成功 . 那么,该怎么做?

谢谢

1 回答

  • 2

    你有多种选择 . 第一种是在为委托创建 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 .

相关问题