How to connect a property signal to a Javascript function.
-
wrote on 15 Feb 2013, 17:36 last edited by
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?
-
wrote on 15 Feb 2013, 18:14 last edited by
Did you try the Connections qml object?
-
wrote on 15 Feb 2013, 18:34 last edited by
Yes, I tried:
@
Connections
{
target: obj.value;
onValueChanged: console.log('changed');
}
@ -
wrote on 15 Feb 2013, 18:43 last edited by
that should work, maybe you forgot to emit the signal from C++ in the setter?
-
wrote on 15 Feb 2013, 18:46 last edited by
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');
}
@ -
wrote on 15 Feb 2013, 18:51 last edited by
ahh, good catch, I missed that :)
-
wrote on 18 Feb 2013, 00:15 last edited by
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.
3/7