Interact between QML and C++ layer

QML and C++

while creating a Qt quick application, it is impossible to avoid communicate between qml and c++, it can be shown like:

there are some methods, and I like the first one:

call c++ code from qml

create object

class CInterface : public QObject {
  ...
}
#include <QQmlEngine>
...
qmlRegisterType<CInterface>("interface", 1, 0, "interface");

communicate between them

then we use it in qml:

interface {
  id: c_interface
  onSigAction: {
    ...
  }
}
  • qml signal to c++ we assume our object has a slot slotAction in C++ and a signal sigQml in QML:
    class CInterface : public QObject {
    ...
    public slots:
    void slotAction();
    }
    

and the QML part:

interface {
  id: c_interface
}
...
Component.onCompleted: {
  c_interface.slotAction();
}

and the QML part:

interface {
  id: c_interface
}
...
Component.onCompleted: {
  c_interface.action();
}

type between qml and c++

there are usually used types between c++ and qml, you can refer here to find you want to use:

Qt Type QML Type
bool bool
unsigned int, int int
double double
float, qreal real
QString string
QVariant var

call qml from c++

in this case, you have to set the objectName for the object you want to call from c++

Rectangle {
  id: "rect"
  objectName: "rectObj"
  ...
}

then you can find the object from c++

QQuickItem *item = engine.findChild<QQuickItem*>("rectObj");