Solved QML switch not working as expected with bind c++ property
-
Hi all,
Suppose I've a c++ object (derived from QObject) which exposes a property using the Q_PROPERTY macro. Whenever I bind this property to the checked property of a QML switch it reacts properly to the notify signal (changes from c++ code are properly propagated). But when I change the checked state of the switch by clicking on it, it will not call the respective set function of the bind property.
Some code to reproduce it:
CppObject.h
class CppObject : public QObject { Q_OBJECT Q_PROPERTY(bool active READ active WRITE setActive NOTIFY activeChanged) public: explicit CppObject(QObject *parent = nullptr) {} bool active() const { return m_active; } void setActive(bool active) { if (m_active != active) { m_active = active; emit activeChanged(); } } signals: void activeChanged(); private: bool m_active; };
Part of main.ccp
CppObject obj; engine.rootContext()->setContextProperty("cppObject", &obj); engine.load(QUrl(QLatin1String("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec();
main.qml
ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Hello World") Switch { id: switch2 checked: cppObject.active } }
I'm using Qt 5.9.1 and QtQuick.Controls 2.2. Does someone experience the same behaviour?
-
Bindings are not bidirectional. If you want switch2.checked =>cppObject.active as well as cppObject.active => switch2.checked, the connection needs to be explicitly stated.
-
Thanks for the clarification @jeremy_k. I was always under the impression that property binding was bidirectional, mainly due to the Q_PROPERTY read and write parameters/functions. I think however that it is a bit lame that it can automatically read values by the getter but lacks the setter functionality.
-
@bludger said in QML switch not working as expected with bind c++ property:
I think however that it is a bit lame that it can automatically read values by the getter but lacks the setter functionality.
The setter isn't missing. The program[mer] has to tell the runtime what to connect the input of that setter to. It's no less automatic than the getter, which also requires an explicit reference to the property.