2017-08-04 147 views
0

我有一個Qt應用程序,它調用主要QML組件的qt_update_values()。我想將新值發送給特定的代理。我如何連接update_values()從主要組件接收特定的子組件,它是在另一個qml中定義的?從主組件到子組件的QML連接信號

我試圖確定在孩子的連接,但我不知道什麼樣的目標,我需要定義...

main.qml我有一些與此類似:

... 
signal update_values(new_values) 

function qt_update_values(newValues){ 
    update_values(newValues); 
} 

Repeater { 
    id:idRepeater 
    model: 3 

    Rectangle { 
     id:example 

     Text{ text: "hello"} 
     ... 

     AnotherComponent {name: "name", othervariables: "others"} 
    } 
} 
... 

然後在AnotherComponent.qml我有:

... 
signal update_values_child(new_values) 

function onUpdate_values(newValues){ 
    textid = newValues; 
} 

Text{ id:textid} 
... 

回答

0

你不從父連接到主,但周圍的其他方法是這樣的:

... 
id: idOfTheParent // <=== THIS IS IMPORTANT 
signal update_values(new_values) 

function qt_update_values(newValues){ 
    update_values(newValues); 
} 

Repeater { 
    id:idRepeater 
    model: 3 

    Rectangle { 
     id:example 

     Text{ text: "hello"} 
     ... 

     AnotherComponent { 
      id: idOfAnotherComponent // This ID is only available in the 
            // scope of the Component 
            // that will be instantiated by the 
            // Repeater, i.e. children of the Rectangle 
      name: "name" 
      othervariables: "others" 
     } 
     Connections { 
      target: idOfTheParent 
      onUpdate_values: idOfAnotherComponent.dosomethingWith(new_values) 
     } 
    } 
} 
... 

你也可以使用signal.connect()添加新的連接

Repeater { 
    model: 10 
    delegate: Item { ... } 
    onItemAdded: { 
     idOfTheParent.update_values.connect(function() { // do what you want }) 
    } 
} 

但如果它僅僅是一個新的價值的廣播中,聲明的辦法是,在你委託給具有屬性,他們綁定到舉行的量變到質變值的屬性:

... 
id: idOfTheParent 
property var valueThatWillChange 

Repeater { 
    model: 10 
    delegate: Item { 
     property int valueThatShallChangeToo: idOfTheParent.valueThatWillChange 
    } 
} 
... 

用c的不同信號來完成它。是可能的:

對於Connections - 溶液最簡單的事情就是打電話doSomething只有當它是正確的委託實例:

// in the delegate 
Connections { 
    target: idOfTheParent 
    onValue1Updated: if (index === 1) doYourStuff() 
    onValue2Updated: if (index === 2) doYourStuff() 
    onValue... 
} 

但是,這是第二種方法更簡單:

id: idOfTheParent 
Repeater { 
    model: 10 
    delegate: SomeItem { 
     function doSomething() { console.log(index, 'does something') 
    } 
    onItemAdded: { 
     idOfTheParent['value' + index + 'Updated'].connect(item.doSomething) 
    } 
    onItemRemoved: { 
     idOfTheParent['value' + index + 'Updated'].disconnect(item.doSomething) 
    } 
} 
+0

謝謝你@derM。它實際上不僅僅是更新...我嘗試了第一種方法,並且沒有發生錯誤,但是我已經在代理中的dosomethingWith(new_values)上設置了一個console.log,並且它沒有顯示任何內容。好像該函數沒有被調用... – laurapons

+1

對不起,我忘了在最後添加參數。有用!謝謝!!! @derM – laurapons

+0

最後一個問題,有沒有什麼辦法只連接特定的代表,而不是全部(在我的例子中,代表將是一系列動態的圖表)。我想用不同的qt_update_value_chart1或qt_update_value_chart2連接每個圖表......有可能嗎? @真皮 – laurapons