QML 将信号从主组件连接到子组件

问题描述 投票:0回答:1

我有一个 Qt 应用程序,它调用

qt_update_values()
主要 QML 组件。我想将新值发送给特定的代表。如何从主组件连接
update_values()
以便由另一个 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}
...
qml signal-handling qqmlcomponent
1个回答
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
    }
}
...

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

对于

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)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.