Introduction
QT QML will helps us to build the User Interface quickly and elegantly, It acts as a UI Presentation Layer. There should be a way of communicating data from C++ to QML. This article describes the simplest way of data binding between QML and C++ which uses the following features:
Q_PROPERTY
in C++ which will give the set
and get
methods for C++ as well as QML. - QT way of registering the C++ Object, which makes the way to import that object in QML.
- In QML, we can
set
and get
the properties by attaching the C++ object to it.
Using the Code
Smooth way of communication can be handled between QML and C++.
#pragma once
#include <QObject>
class propertybinding : public QObject
{
Q_OBJECT
Q_PROPERTY(QString valueToQML READ valueToQML WRITE setValueToQML NOTIFY valueToQMLChanged)
public:
explicit propertybinding(QObject *parent = 0);
~propertybinding();
QString valueToQML() const;
void setValueToQML(QString);
signals:
void valueToQMLChanged();
private:
QString _valueString;
};
#include "propertybinding.h"
propertybinding::propertybinding(QObject *parent) : QObject(parent) { }
propertybinding::~propertybinding() { }
void propertybinding::setValueToQML(QString pData) {
_valueString = pData;
emit valueToQMLChanged();
}
QString propertybinding::valueToQML() const {
return _valueString;
}
import QtQuick 2.3
import PropertyBinding 1.0
Rectangle {
property alias mouseArea: mouseArea
PropertyBinding {
id: propertyBinding
}
width: 400
height: 400
MouseArea {
id: mouseArea
anchors.rightMargin: 0
anchors.bottomMargin: 0
anchors.leftMargin: 0
anchors.topMargin: 0
anchors.fill: parent
Text {
id: text1
x: 115
y: 27
width: 145
height: 32
text: qsTr("Property Binding")
font.pixelSize: 22
}
Text {
id: text2
x: 109
y: 103
width: 41
height: 15
text: qsTr("Value:")
font.pixelSize: 12
}
Row {
id: row1
x: 88
y: 73
width: 200
height: 75
}
Text {
id: text3
x: 190
y: 103
width: 53
height: 15
text: propertyBinding.valueToQML font.pixelSize: 12
}
}
Component.onCompleted: propertyBinding.valueToQML =
"QML to C++ Property Binding" }
Points of Interest
Q_PROPERTY
mechanism - qml registertype for accessing the C++ Object
- Using C++ object in QML Land