Connect to C++ signal from QML
-
Hi! I want to connect to C++ signals from QML like this:
action.onMouseUp = function() { console.log("mouse up>>"); }
And declare in my C++ object this signal:
signals: void mouseUp(const QPointF point);
But I'm getting QML Error: TypeError: Cannot assign to read-only property "mouseUp". What might the problem be?
-
@Rem-Kolomna That is because you are trying to assign the function to that signal.
Use Connections instead.Connections { target: action //if action is the target object onMouseUp: console.log(point) }
-
Yeah, connection is a way to go, but I want to simplify qml code and write it like that:
action.onMouseUp = function()
It is one line instead of four lines))) May be I can use Q_QROPERTY(QJSValue...) for this task?
-
@Rem-Kolomna You can't as
mouseUp
is a signal. You get something from signal and not give it. -
@Rem-Kolomna You can also use a
connect
method. Eg:Component.onCompleted: { action.mouseUp.connect( function getPoint(myPoint) {console.log(myPoint) } ); }
-
@Rem-Kolomna said:
action.onMouseUp = function() { console.log("mouse up>>"); }
Try replacing that with
action.onMouseUp: { console.log("mouse up>>"); }
@p3c0 said:
@Rem-Kolomna You can't as
mouseUp
is a signal. You get something from signal and not give it.If
mouseUp
is the signal, thenonMouseUp
is the signal handler. -
@JKSH Right. I was just trying to explain that signals and the corresponding handlers cannot be assigned anything which produced that earlier error.
-
I found a simple solution for my problem. I just declare a property
Q_PROPERTY(QJSValue onMouseUp READ onMouseUp WRITE setOnMouseUp)
that I can call from C++ side as QJSValue::call(). It allows me to write more clean code and ensure to have a single signal handler for this event (it's also important for me)