Sunday, June 3, 2018

QML signals to C++? No, the other way around please

While developing an application with QML and C++ please refrain to emit signals in QML that should be handled by C++ code. Just the opposite, keep QML as the UI layer and expose your C++ object to QML (as a context property or with qmlRegisterXXX) and then call a slot or a Q_INVOKABLE method of this object from QML.

DO NOT (in C++):
QObject::connect(window, SIGNAL(qmlSignal(QString)), &myClass, SLOT(cppSlot(QString)));

DO (in QML)
onClicked: cppObject.cppSlot("on")

Not reaching into your UI layer from c++ will allow to keep a clean codebase and easier refactoring. Some more in-depth reasoning in this very good talk. Just a take away of all this: always go from QML to C++ (I think C++ code as a "library" used by QML code).






No comments:

Post a Comment