2017-02-23 28 views
1

我有以下qml文件,main.qml创建TestWindow.qml元素。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?

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

谢谢

回答

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,它得到时销毁。

我推荐前者,如果你想连接是永久性的,而后者,如果你可能要在一段时间内断开。

onItemAdded/onRemoved处理程序,如果你不为Repeater声明delegate尤为重要。例如,如果您使用DelegateModelObjectModel,则会发生这种情况。与这些模型,你不能确定,对象实例化或破坏时Repeater添加或删除它们,你不能使用经常提到:Component.onCompleted/onDestruction,所以我认为itemAdded/Removed -signals上/更普遍的使用与Repeater