QLineSeries和QDateTimeAxis-图表不显示值

时间:2018-09-25 21:39:52

标签: c++ qt qchart qchartview

我正在尝试实现https://doc.qt.io/qt-5.9/qtcharts-datetimeaxis-example.html之类的东西。

在一种方法中,我有这段代码

QDateTime past = QDateTime::currentDateTime().addMonths(-10);
QDateTime now = QDateTime::currentDateTime();
qreal pastvalue = 4;
qreal nowvalue = 4;
axisY = new QValueAxis();
axisX= new QDateTimeAxis();
chart = new QChart();
series = new QLineSeries();
/*Y*/
axisY->setLabelFormat("%i");
axisY->setTitleText("Numero dispositivi");
axisY->setMin(0);
axisY->setMax(5);
/*X*/
axisX->setTickCount(2);
axisX->setMin(past);
axisX->setMax(now);
axisX->setFormat("dd-MM-yyyy h:mm:ss"); 
/*series/*
series->attachAxis(axisX);
series->attachAxis(axisY);
series->append(past.toSecsSinceEpoch(),pastvalue);
series->append(past.toSecsSinceEpoch(),nowvalue);
/*chart*/
chart->legend()->hide();
chart->setTitle("Dati filtrati durante il periodo temporale");
chart->addAxis(axisY, Qt::AlignLeft);
chart->addAxis(axisX, Qt::AlignBottom);
chart->addSeries(series);

chartView = new QChartView(chart);
ui->verticalLayout->addWidget(chartView);

我不明白为什么不显示值。

我不知道怎么了。

1 个答案:

答案 0 :(得分:0)

您的代码具有以下错误:

  • 您必须使用toMSecsSinceEpoch()而不是toSecsSinceEpoch()
  • 您必须先将轴添加到QChart,然后才能将其附加到序列上。
  • series->append(past.toSecsSinceEpoch(),nowvalue);更改为series->append(now.toMSecsSinceEpoch(),nowvalue);

  • 我建议您设置刻度线,以便仅显示整个点,因为例如,不合适的值将显示在垂直轴上,或者设置为带有小数位数的浮点数。下图显示了%i的结果:

enter image description here

如上图所示,4非常接近3且比5远,而不是等距,因此在我建议的解决方案中,将使用%.2f:

QDateTime past = QDateTime::currentDateTime().addMonths(-10);
QDateTime now = QDateTime::currentDateTime();
qreal pastvalue = 4;
qreal nowvalue = 4;
axisY = new QValueAxis();
axisX= new QDateTimeAxis();
chart = new QChart();
series = new QLineSeries();
/*Y*/
axisY->setLabelFormat("%.2f");
axisY->setTitleText("Numero dispositivi");
axisY->setMin(0);
axisY->setMax(5);
/*X*/
axisX->setTickCount(2);
axisX->setMin(past);
axisX->setMax(now);
axisX->setFormat("dd-MM-yyyy h:mm:ss");
/*series*/

series->append(past.toMSecsSinceEpoch(),pastvalue);
series->append(now.toMSecsSinceEpoch(),nowvalue);
/*chart*/
chart->legend()->hide();
chart->setTitle("Dati filtrati durante il periodo temporale");
chart->addAxis(axisY, Qt::AlignLeft);
chart->addAxis(axisX, Qt::AlignBottom);
chart->addSeries(series);
series->attachAxis(axisX);
series->attachAxis(axisY);

chartView = new QChartView(chart);
ui->verticalLayout->addWidget(chartView);

enter image description here