PDA

View Full Version : Access caller qml-Object from C++ Object



xdn
13th February 2013, 15:06
Hi everyone,

I have a qml file that is loaded using a QDeclarativeView in a small main application.
The qml file uses a C++ class (call it MyClass) and in case of a click event calls a method from that class (say Q_INVOKABLE void MyClass::handleClick()).
From that method I would now like to access elements of the qml Gui. How is this possible? Is there something equivalent to what QObject::sender() does in Qt slots?

I know that I could emit a signal at the end of MyClass::handleClick() and connect that with a slot in the qml file to solve this but I'd rather have access to the qml file directly (at least to know how it's done).

wysota
13th February 2013, 17:36
You can get access to QML elements with QDeclarativeContext and its contextProperty() method.

However I'd advise against accessing QML elements from C++. Normally you'd rather do the opposite.

xdn
13th February 2013, 19:23
So you would recommend that emitting a signal and then handling the rest in a qml slot stuff I wrote above?!
Or is there another (cleaner/more recommended) way?

wysota
13th February 2013, 20:30
So you would recommend that emitting a signal and then handling the rest in a qml slot stuff I wrote above?!
Or is there another (cleaner/more recommended) way?

I have no idea what your code is meant to do so it is hard to suggest a good solution. I can only say that going from UI stuff to logic and then back to UI is likely a bad design.

anda_skoa
14th February 2013, 03:25
I can only say that going from UI stuff to logic and then back to UI is likely a bad design.

Not necessarily.
The logic could reach a state where user input is required so it has to delegate back to the UI.

Consider a case where the UI provides a way for the user to trigger saving of data. This would very likely call into the C++ core to do the actual saving.
If that code then discovers that there is no know filename yet, it somehow has to ask the UI to ask the user for one.

I do agree of course that accessing UI elements from logic is a no-go, but signalling the UI to do something sounds very reasonable.

Cheers,
_

wysota
14th February 2013, 10:58
If that code then discovers that there is no know filename yet, it somehow has to ask the UI to ask the user for one.
I think it should return information to the UI that it can't save the file because of a missing filename, the UI should ask the user for the filename and then call the save routine again. Or the logic should explicitly offer the filename to the UI and the UI should first check if it is valid or not and then call the saving routine. Doing what you suggest if of course possible and acceptable and I would probably do that myself in many cases however in theory I would still consider it bad design because of two direction coupling of components (UI had to know about logic and logic has to know about UI).