Search code examples
qtchartsqmllineseries

QML, create LineSeries at runtime


My goal is to have a QML ChartView with a variable number of LineSeries added to it during runtime. It is unknown how many LineSeries will need to be added until a user selects and loads a file with the data in it.

I tried to create all of the LineSeries inside a Repeater, with no luck. I suspect it's because ChartView doesn't know what to do with a bunch of Item's. It's not possible to have the Repeater create LineSeries directly since a Repeater doesn't work on QObject's:

Repeater {
    model: numberOfColumnsInModel / 2

    delegate: Item {
        LineSeries {
            id: lineSeries
            axisX: xAxis
            axisY: yAxis

            VXYModelMapper {
                id: modelMapper
                model: lineChart.model //Reimplemented QAbstractTableModel
                xColumn: index * 2
                yColumn: index * 2 + 1
            }

            onHovered: {
                console.log("Do something...");
            }
        }
    }
}

In the examples I see online, each LineSeries is hard-coded--once for each line in the ChartView--and not useful to me.


Solution

  • Use force documentation, Luke. In the example below random count of lines with random count of points are created at starting up:

    import QtQuick 2.7
    import QtQuick.Window 2.2
    import QtQuick.Controls 2.0
    import QtCharts 2.1
    
    Window {
        id: window1
        title: "Chart test"
        visible: true
        width: 600
        height: 400
    
        ChartView {
            id: chart
            anchors.fill: parent
            axes: [
                ValueAxis{
                    id: xAxis
                    min: 1.0
                    max: 10.0
                },
                ValueAxis{
                    id: yAxis
                    min: 0.0
                    max: 10.0
                }
            ]
            Component.onCompleted: {
                var seriesCount = Math.round(Math.random()* 10);
                for(var i = 0;i < seriesCount;i ++)
                {
                    var series = chart.createSeries(ChartView.SeriesTypeLine, "line"+ i, xAxis, yAxis);
                    series.pointsVisible = true;
                    series.color = Qt.rgba(Math.random(),Math.random(),Math.random(),1);
                    series.hovered.connect(function(point, state){ console.log(point); }); // connect onHovered signal to a function
                    var pointsCount = Math.round(Math.random()* 20);
                    var x = 0.0;
                    for(var j = 0;j < pointsCount;j ++)
                    {
                        x += (Math.random() * 2.0);
                        var y = (Math.random() * 10.0);
                        series.append(x, y);
                    }
                }
            }
        }
    }