Important: Please read the Qt Code of Conduct -

What is the best way to change attributes in QML from C++

  • Hi,

    what is the best way to change attributes in QML from C++? I know that there are different solutions to this problem.

    This are the solutions I know:
    1. Solution
    Set a context property in c++ (e.g. Rotation) and read it in QML.
    @this->rootContext()->setContextProperty("var", var);@
    @rotation: var@

    2. Solution
    Emmit a signal in c++ and connect it with a slot in QML.
    @emit started(var);@
    @onStarted: rotation(value)@

    3. Solution
    Use a javascript function inside your QML and invoke it from C++.
    To be honest I don't like this approach. QML should cover only the UI and C++ the logic.
    Writing a javascript function into your QML file, adds logic to the UI. -> maintanence and bug fixing gets more difficult
    That's why I won't use this approach.

    So, any suggestions (regarding performance or improvment) about the different ways to handle this problem?
    Or do you even know any other way to change attributes from QML?

  • Moderators

    This doc mentions a few additional approaches: "LINK":

  • Moderators

    And about your 3rd solution: don't dismiss it that fast. JS capabilities in QML are quite useful, and there may be use cases, where this would be favourable.

    In an app I'm currently writing, I am using JS quite a lot, because it's simply easier to write some functions in it (especially ones that reference a lot of other QML objects visible in a file), than going back to C++ and throwing in a lot of qobject_casts etc. I might transfer some functions to C++ later on, but still, a lot will probably remain where they are.

  • Thanks for the quick response.
    I would like to know if there is a performance difference between these approaches.

    Regarding the link you sent me:
    I had given it a short look already, but it doesn't cover the performance questions.
    Another thing would be that I would like to send a signal from c++ to a rectangle in QML (not an own object).
    Any ideas how I could do that?

  • Moderators

    I have not benchmarked those, nor have I heard about any benchmark done anywhere. But, all those approaches make use of Qt's Meta Object System, so most probably performance of all of them is quite similar (nonetheless, check for yourself to be sure, that's just a guess).

  • Ok thank you.

Log in to reply