正如@eyllanesc 在他的回答中所解释的那样,无法使用DateTimeAxis
来获取您想要显示的内容。
这里有一些代码可以帮助生成与使用CategoryAxis
.
注意:在我的示例中,数据是在 QML 中创建和格式化的,但是您可以在数据实际可能存在的 C++ 部分中执行此操作。
import QtQuick 2.9
import QtCharts 2.2
Item {
id: root
width: 1280
height: 720
ListModel {
id: data
function toMsecsSinceEpoch(date) {
var msecs = date.getTime();
return msecs;
}
Component.onCompleted: {
var minDate = data.get(0).x;
var maxDate = data.get(0).x;
var minValue = data.get(0).y;
var maxValue = data.get(0).y;
// Find the minimum and maximum values.
// Fill the SplineSeries data.
for (var i = 0 ; i < data.count ; i++) {
if (data.get(i).x < minDate)
minDate = data.get(i).x;
if (data.get(i).x > maxDate)
maxDate = data.get(i).x;
if (data.get(i).y < minValue)
minValue = data.get(i).y;
if (data.get(i).y > maxValue)
maxValue = data.get(i).y;
chartseries.append(data.get(i).x, data.get(i).y);
}
// Fill the axis limits (x-axis and y-axis).
axisY.min = Math.floor(minValue)
axisY.max = Math.ceil(maxValue)
xTime.min = minDate;
xTime.max = maxDate;
// Fill the CategoryAxis (x-axis).
var dateReference = new Date(xTime.min);
while (dateReference < xTime.max) {
xTime.append(Qt.formatDate(dateReference, "MMM yyyy"), toMsecsSinceEpoch(new Date(dateReference.getFullYear(), dateReference.getMonth(), 1)));
dateReference.setMonth(dateReference.getMonth() + 1);
}
xTime.append(Qt.formatDate(dateReference, "MMM yyyy"), toMsecsSinceEpoch(new Date(dateReference.getFullYear(), dateReference.getMonth(), 1)));
}
ListElement { x: 1514770200000; y: 40.311 }
ListElement { x: 1517434200000; y: 40.4664 }
ListElement { x: 1519853400000; y: 39.6276 }
ListElement { x: 1522531803000; y: 39.6238 }
ListElement { x: 1525123806000; y: 40.3 }
ListElement { x: 1527802210000; y: 40.5638 }
}
ChartView {
id: chart
anchors.fill: parent
antialiasing: true
ValueAxis {
id: axisY
tickCount: 3
min: 39
max: 41
}
CategoryAxis {
id: xTime
labelsPosition: CategoryAxis.AxisLabelsPositionOnValue
}
SplineSeries {
id: chartseries
pointsVisible: true
pointLabelsVisible: false
useOpenGL: true
axisX: xTime
axisY: axisY
}
}
}