2017-08-04 148 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