Home > other >  When using Qt's QChartView to draw a line chart, the category name represented by the line cann
When using Qt's QChartView to draw a line chart, the category name represented by the line cann

Time:10-18

#include <QApplication>
#include <QMainWindow>
#include <QDateTime>
#include <QChartView>
#include <QLineSeries>
QT_CHARTS_USE_NAMESPACE

int main(int argc, char **argv) {
    QApplication application(argc, argv);

    auto *series01 = new QLineSeries();
    series01->setName("line01");
    ...

    auto *series02 = new QLineSeries();
    series02->setName("line02");
    ...

    auto *chart = new QChart();
    chart->legend()->hide();
    chart->addSeries(series01);
    chart->addSeries(series02);
    series01->setUseOpenGL(true);
    chart->createDefaultAxes();
    chart->setTitle(QStringLiteral("Qt line chart example"));

    auto *view = new QChartView(chart, nullptr);
    view->setRenderHint(QPainter::Antialiasing);
    view->resize(1000, 600);
    view->show();

    return QApplication::exec();
}

The current line chart looks like this:

enter image description here

How can I display their respective names for these two lines?

enter image description here

You only need to display their names, and the colors need to correspond, and the position and shape are not necessary.

CodePudding user response:

This happens because you hide legend

#include <QApplication>
#include <QMainWindow>
#include <QDateTime>
#include <QChartView>
#include <QLineSeries>

QT_CHARTS_USE_NAMESPACE

int  main(int argc, char **argv)
{
    QApplication  application(argc, argv);
    auto         *series01 = new QLineSeries();

    series01->setName("line01");

    series01->append(0, 0);
    series01->append(2, 5.5);
    series01->append(3.2, 8);
    series01->append(8, 9);
    series01->append(11, 4);

    auto *series02 = new QLineSeries();
    series02->setName("line02");

    series02->append(0, 0);
    series02->append(1.5, 2);
    series02->append(4, 4);
    series02->append(6, 6);
    series02->append(7.5, 8);
    series02->append(7.5, 1);
    series02->append(8.1, 5);

    auto *chart = new QChart();
// chart->legend()->hide();
    chart->addSeries(series01);
    chart->addSeries(series02);
    series01->setUseOpenGL(true);
    chart->createDefaultAxes();
    chart->setTitle(QStringLiteral("Qt line chart example"));

    auto *view = new QChartView(chart, nullptr);
    view->setRenderHint(QPainter::Antialiasing);
    view->resize(1000, 600);
    view->show();

    return QApplication::exec();
}

enter image description here

  • Related