Getting reference to dynamically created ChartView
-
I am trying to get a reference to a dynamically created ChartView object. In the code you will see I dynamically create a Chart as the Delegate when I click the 'add chart' button.
import QtQuick 2.12 import QtQuick.Window 2.12 import QtCharts 2.3 import QtQuick.Controls 2.4 import "Utils.js" as Utils Window { visible: true width: 1200 height: 800 title: qsTr("GridViewDemo") ListModel { id: modelId } Rectangle { id: rectId color: "pink" anchors.fill: parent GridView { id: mGridViewId anchors.fill: parent cellWidth: 300; cellHeight: 300 model: modelId delegate: Rectangle { width: mGridViewId.cellWidth; height: mGridViewId.cellHeight color: mColor ChartView { width: parent.width; height: parent.height LineSeries { name: "LineSeries" XYPoint { x: 0; y: 0 } XYPoint { x: 1.1; y: 2.1 } XYPoint { x: 1.9; y: 3.3 } } } } } } Column { anchors.centerIn: parent Row { Button { text: "add chart" onClicked: { modelId.append({'mColor': 'blue'}) } } Button { text: "remove chart" onClicked: { modelId.remove(0) } } } Button { anchors.horizontalCenter: parent.horizontalCenter text: "add line series" onClicked: { var chart = modelId.get(0) chart.removeAllSeries(); } } } }
I am able to get a reference to a specific item of the Model using :
var chart = modelId.get(0)
However it is not treated as a Rectangle nor a ChartView. So if I wanted to do something like add a LineSeries to one of the dynamically created Charts, or remove LineSeries like so:
onClicked: { var chart = modelId.get(0) chart.removeAllSeries(); }
I am unable to treat the object as a QML object. I get an error:
qrc:/main.qml:80: TypeError: Property 'removeAllSeries' of object QObject(0x7fd35d996b50) is not a function
I am not sure what I am doing this wrong or if I need to go about this in a totally different way, i.e. not using ListView-Model-Delegate and instead dynamically create a QML object and store references to them in an array.
Thanks for any help, I appreciate it.
--E
-
If you want to get the items created dynamically, use contentItem property of view. It should help you.
-
Thank you @dheerendra you certainly pointed me in the right direction. After looking into contentItem property derived from Flickable I was able to access the dynamically created item by adding this function to the GridView
function getDelegateInstanceAt(index) { return contentItem.children[index]; }
and to modify the specific delegate call the function passing the index
onClicked: { var chart = mGridViewId.getDelegateInstanceAt(2); chart.removeAllSeries(); }
Thank you sir. Solved