QML QtChart 中 DateTimeAxis使用

QtChart曲线设置时间轴需要用到QDateTimeAxis。在这里主要介绍QML中的使用。

QML中需要用到DateTimeAxis,同时介绍使用QML中的Date对象。

看一下效果

QML QtChart 中 DateTimeAxis使用_第1张图片

具体代码如下:

import QtQuick 2.9
import QtCharts 2.2


ChartView{

    Rectangle{
        width: 20; height: 20
        color: "red"
        MouseArea
        {
            anchors.fill: parent
            onClicked: {
                console.log(startdate)
                var curd = new Date();
                console.log(curd.toString());

                curd.setHours(curd.getHours()+6);
                console.log(curd.toString());

                var maxtimestr = curd.toLocaleString(Qt.locale(),"yyyy-MM-dd hh:mm:ss");
                topline.append(x_axis.min.getTime(),80);

                for (var i = 0; i < 100; ++i)
                {
                    line.append(1525837369967+i*1000*500,Math.random()*100);
                }

                x_axis.max =  Date.fromLocaleString(Qt.locale(), maxtimestr, "yyyy-MM-dd hh:mm:ss")
                topline.append(x_axis.max.getTime(),80);

            }
        }
    }

    id : view
    anchors.fill: parent
    antialiasing: true
    legend.visible : false
    property real lablefont: 15
    property date curdate: new Date()
    property var startdate: "2018-05-09 12:00:00"
    //property string enddate:


    DateTimeAxis {
        id : x_axis
        min : Date.fromLocaleString(Qt.locale(), view.startdate, "yyyy-MM-dd hh:mm:ss")
        max : Date.fromLocaleString(Qt.locale(), "2018-05-09 20:00:00", "yyyy-MM-dd hh:mm:ss")
        format: "hh::mm" //设置显示样式
        labelsFont.pointSize: view.lablefont

    }
    ValueAxis {
        id : y_axis
        min : 0;
        max : 100;
        labelFormat: "%i" //设置标签的显示精度 样式
        labelsFont.pointSize: view.lablefont
    }

    AreaSeries
    {
        axisY: y_axis;
        axisX: x_axis
        color: "#99CA53"
        upperSeries : LineSeries
        {
            id : line;
            useOpenGL: true
        }
    }
    LineSeries {
        id : topline;
        axisX: x_axis
        axisY: y_axis;
        color: "red"
    }

    //加载完成时设置x的坐标轴
    Component.onCompleted:
    {
        var curd = new Date();
        var mintimestr = curd.toLocaleString(Qt.locale(),"yyyy-MM-dd hh:mm:ss");
        curd.setHours(curd.getHours()+6);
        var maxtimestr = curd.toLocaleString(Qt.locale(),"yyyy-MM-dd hh:mm:ss");
        //x_axis.min =  Date.fromLocaleString(Qt.locale(), mintimestr, "yyyy-MM-dd hh:mm:ss")
        //x_axis.max =  Date.fromLocaleString(Qt.locale(), maxtimestr, "yyyy-MM-dd hh:mm:ss")

    }            

}

注意:添加数据时,x轴的值需要是 到毫秒。使用QDateTime::toMSecsSinceEpoch(),而不要QDateTime::toTime_t ()。 





你可能感兴趣的:(Qt,qml,QtChart)