Important: Please read the Qt Code of Conduct -

Call a function every time a variable is changed

  • Hi,

    Is it possible to automatically call a function every time a specified variable is changed?

  • I believe there is a way if it is a "property" inside a QML component, then you get a onVariableNameChanged and you can call whatever you would like there


    property string myVar: "default_value"

    onMyVarChanged: { // call your function here }

    Hope this helps!!

  • No, there is not. If you want that, then you should make your variable private to a class, and create a public accessor method for it. So:
    //old situation
    int value;

    //somewhere in code
    value = 10;

    //new situation:
    int value;
    void setValue(int newValue) {value = newValue; /* whatever else you need to do*/}

    //somewhere in code:

  • Okay. Thanks for the replies:) I think I will go with the last one.

  • Oh, haha one was using QML, the other Qt C++,

    If you want to go the C++ route there is this page "Qt Bindings":

    Which may help you... I believe they use signals inside the C++ code as well as using the Q_PROPERTY macro

Log in to reply