How to connect a property signal to a Javascript function.
-
I'm new to Qml and having some trouble connecting a javascript handler to a property's signal. I have a C++ object with a property and signal.
@
class CppObject : public QObject
{
Q_OBJECT
Q_PROPERTY(QVariant value READ getValue WRITE setValue NOTIFY valueChanged)signals: void valueChanged(const QVariant &); };
@
The objects are created through a C++ factory method and I'm able to bind the values
and changes to Qml properties. This all works.@
property CppObject obj: cppProxy.PropertyFactory("foo");Text { x: 100; y: 100; text: parent.obj.value; }
@
For some properties, I'd like to connect the valueChanged signal to a javascript function.
I've been up and down through the Qml documentation and have tried a bunch of stuff without
any luck. I figured something like this should work, but doesn't@
function objEventHandler()
{
console.log('objEventHandler() ran')
}Component.onCompleted: { obj.value.valueChanged.connect(objEventHandler); }
@
What is the best way to do this?
-
Yes, I tried:
@
Connections
{
target: obj.value;
onValueChanged: console.log('changed');
}
@ -
Okay, the issue is the target should be the object, not the object's property. So, this works:
@
Connections
{
target: obj;
onValueChanged: console.log('changed');
}
@ -
Note that the "valueChanged" function is a function property of "obj" and not of the "value" property of "obj".
So, instead of:
@
obj.value.valueChanged.connect(objEventHandler)
@you should use
@
obj.valueChanged.connect(objEventHandler)
@Depending on the situation, using a declarative Connections element is better, though (for example, if the target of the dynamic connection can change depending on the situation). In some situations, on the other hand, using an imperative connection can be better (as you don't incur the overhead of constructing an extra QObject).
Cheers,
Chris.