Valentin H
Valentin H

Reputation: 7448

C++ object doesn't get value when connected QML property changes

I have a component in C++ with the property "step":

class cppcomponent   : public QObject
...
Q_PROPERTY(QVariant step READ getStep WRITE setStep NOTIFY stepChanged)

I try to connect this property to QML.

TextInput {
    text: cppcomp.step
}

It works in one direction. QML gets the initial value. However, when I change the value in QML, my setStep method is not called.

It works only, when I set the property of C++ component explicitly in onAccepted:

TextInput {
    text: cppcomp.step
    onAccepted: {
        cppcomp.step = step.text
    }
}

Do I really have to set it explicitly?

Upvotes: 0

Views: 404

Answers (1)

Arpegius
Arpegius

Reputation: 5887

Your code should work well, except that the step might not be defined. If you want to get to TextInput property just omit its id. To confirm that your idea is working correctly, run this code:

    QtObject { //A bare QObject with one property
        id:cppcomp
        property string step: "Working"
    }

    TextInput { 
        text: cppcomp.step+"!"
        onAccepted: cppcomp.step = text
    }

Each time you press the enter when TextInput is focused a new ! should appear.

(Tested with Qt 5.7)

Upvotes: 1

Related Questions