QT chart 注意地方 (QChart::setAxisX/Y)

  • 在使用QChart::setAxisX/Y 之前,QxxxSeries必须要先加载至chart否则没有图上没有数据。正确顺序:
m_chart->addSeries(m_series)
m_chart->setAxisX(axisX,m_series);
m_chart->setAxisY(axisY,m_series);

  • 完整代码如下:
  • MainWindow.cpp构造函数函数内容如下:
    QWidget *mainwidget = new QWidget();
    QHBoxLayout *mainLayout = new QHBoxLayout();
    this->setCentralWidget(mainwidget);
    m_timer =new QTimer();

    m_chart = new QChart();
    chartView = new QChartView(m_chart,this);
    m_series = new QLineSeries();


    QPen green(Qt::green);
    green.setWidth(3);
    m_series->setPen(green);
    m_series->append(0,0.5);
    m_series->append(0.5,0.5);
    m_series->append(1,0.5);
    m_series->append(2,0.5);
    m_series->append(3,0.5);
    *m_series<< QPointF(4, 0.5)<setUseOpenGL(true);


    m_chart->legend()->hide();

    axisX = new QValueAxis();
    axisX->setTickCount(5);
    axisX->setRange(0,10);
    axisX->setTitleText("axisX");
    axisY = new QValueAxis();


    axisY->setRange(0,10);
    axisY->setTitleText("axisY");
   m_chart->addSeries(m_series);
    m_chart->setAxisX(axisX,m_series);//Must be executed "m_chart->addSeries(m_series)" before setAxisX
    m_chart->setAxisY(axisY,m_series);
    m_chart->setTitle("Demo");

    chartView->setRenderHint(QPainter::Antialiasing);
    mainLayout->addWidget(chartView);
    mainwidget->setLayout(mainLayout);
  • MainWindow.h添加以下变量
    QChartView *chartView;
    QChart * m_chart;
    QValueAxis *axisX;
    QValueAxis *axisY;
    QLineSeries *m_series;

你可能感兴趣的:(QT chart 注意地方 (QChart::setAxisX/Y))