Changing the properties of the chart from Qt Widget Application
-
Hello
In my "Qt Widget Application I load a QML object, which is a graph:
ChartView {
title: "Line"
anchors.fill: parent
antialiasing: trueLineSeries { name: "LineSeries" XYPoint { x: 0; y: 0 } XYPoint { x: 1.1; y: 2.1 } XYPoint { x: 1.9; y: 3.3 } XYPoint { x: 2.1; y: 2.1 } XYPoint { x: 2.9; y: 4.9 } XYPoint { x: 3.4; y: 3.0 } XYPoint { x: 4.1; y: 3.3 } }
}
I would like to change the values of the "LineSeries" chart from my application.
In other QML objects, I do it in this way:
QQmlProperty(ui->quickWidget->rootObject(),"currentValue").write(variable);How do you change the "LineSeries" values in the same way?
Best Regards
-
Hi @pirates21. In order to send data to qml components in a Qt Widget Application, you must obtain the QQuickItem* pointer, then you can use two ways (it's possible that exists others but I used these two):
- You can use the SIGNAL/SLOT mechanism.
- You can use the QMetaObject::invokeMethod(...).
Please refer to http://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html.
Good luck.
-
@pirates21
as the docs stateLineSeries
instantiatesQLineSeries
.
So you need a reference to your LineSeries object.QML:
ChartView { title: "Line" anchors.fill: parent antialiasing: true property alias lineSeries: series // <<<<<<<<<< LineSeries { id: series .... } }
Then in C++:
QObject* lineSeriesObj = QQmlProperty(ui->quickWidget->rootObject(),"lineSeries").read().value<QObject*>(); QLineSeries* lineSeries = qobject_cast<QLineSeries*>(lineSeriesObj); lineSeries->clear(); lineSeries->append( ... );
Note that i've haven't tested this code. I don't know if thats enough to also let the chart view also update itself.
-
@raven-worx: You are Genius! Thank You very much!
-
What @raven-worx showed is not recommended (cf. http://doc.qt.io/qt-5/qtqml-cppintegration-overview.html#interacting-with-qml-objects-from-c & https://youtu.be/vzs5VPTf4QQ?t=23m20s & https://doc.qt.io/qt-5/qtquick-bestpractices.html#interacting-with-qml-from-c)
Accessing a QML object from C++ add unnecessary coupling. Your c++ business layer should merely expose data that is then used by the QML layer.
Here what you could do instead is expose a c++
QAbstractListModel
, and use that in QML with aVXYModelMapper
.Alternatively, you could pass your line series to your c++ layer via a slot (or invokable function) and it will then populate it. Your c++ code will still modify a qml object, but at least it didn't have to retrieve it by itself. It's less than ideal but still better.