How do i send a value from main.cpp into Qml file within my qt quick project
transform: Rotation {
id: needleRotation
origin.x: 5; origin.y: 65
angle: -120 + VALUE*2
}
I need the value from Cpp frequently for a speedometer made with qt quick 2.0
I guess the property is produced by some object. In that case you can exploit Q_PROPERTY (see here).
Following what is shown in the link I provided you can rewrite your class as follows:
class DataProvider : public QObject
{
Q_OBJECT
Q_PROPERTY(qreal value READ value WRITE setValue NOTIFY valueChanged)
public:
void setValue(qreal newVal) { // <--- do your stuff to update the value
if (newVal != m_value) {
m_value = newVal;
emit valueChanged(); // <--- emit signal to notify QML!
}
}
qreal value() const {
return m_value;
}
signals:
void valueChanged(); // <--- actual signal used as notification in Q_PROPERTY
private:
qreal m_value; // <--- member value which stores the actual value
};
Here we defined a property value with the corresponding getter and setter (value and setValue resp.) The setter method emits the notification signal which is fundamental to notify QML when the value is changed.
Now, to expose the object to QML (and hence its property) just register it as a context property; just write in your main:
DataProvider data;
engine.rootContext()->setContextProperty("data", &data); // ALWAYS before setting the QML file...
Now the DataProvider instance data can be used through the name data inside QML. Simply rewrite your QML like this:
transform: Rotation {
id: needleRotation
origin.x: 5; origin.y: 65
angle: -120 + data.value * 2
}
Each time you call setValue() in your C++ code and a change occurs to the value, a notification is issued and the binding revaluated.
Q_PROPERTY is the answer.
For general inf on properties: http://qt-project.org/doc/qt-4.8/qml-extending.html.
Look for Q_PROPERTY in this article: http://qt-project.org/doc/qt-5/properties.html.
The second article is a must for C++/QML development (read the whole article). And more recent and structured info: http://qt-project.org/doc/qt-5/qml-extending-tutorial-index.html
I read the second and that still works but it makes sense to revisit with new docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With