c++qtqchartqchartview

QLineSeries and QDateTimeAxis - Chart doesn't display values


I am trying to achieve something like https://doc.qt.io/qt-5.9/qtcharts-datetimeaxis-example.html .

In a method I have this code

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);

I don't understand why values are not displayed.

I can't figure out what's wrong.


Solution

  • Your code has the following errors:

    enter image description here

    As we can see in the previous image, 4 is very close to 3 and farther than 5, instead of being equidistant, so in the solution I propose, you will use %.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