QML 将信号从主要组件连接到 child 个组件

QML connect signal from the main component to the child components

我有一个调用 qt_update_values() 到主要 QML 组件的 Qt 应用程序。我想将新值发送给特定的委托人。如何从主要组件连接 update_values() 以由另一个 qml 中定义的特定 child 组件接收?

我已经尝试在 child 中定义连接,但我不确定我需要定义什么目标...

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}
...

你不是从父连接到主连接,而是像这样反过来:

...
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
    }
}
...

让所有这些都具有不同的信号。可能:

对于 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)
    }
}