qt5.12绘制折线图
时间: 2023-10-01 10:10:19 浏览: 92
QtChart绘制折线图
在Qt5.12中,可以使用Qt Charts模块来绘制折线图。以下是一个简单的示例:
1. 首先,在.pro文件中添加Qt Charts模块的引用:
```
QT += charts
```
2. 在代码中创建一个QChart对象,并将其添加到QChartView中:
```
QChart *chart = new QChart();
QChartView *chartView = new QChartView(chart);
```
3. 创建一个QLineSeries对象并添加数据点:
```
QLineSeries *series = new QLineSeries();
series->append(0, 6);
series->append(2, 4);
series->append(3, 8);
series->append(7, 4);
series->append(10, 5);
```
4. 将QLineSeries对象添加到QChart对象中:
```
chart->addSeries(series);
```
5. 创建一个QValueAxis对象并将其添加到QChart对象中:
```
QValueAxis *axisX = new QValueAxis;
axisX->setRange(0, 10);
axisX->setLabelFormat("%.0f");
axisX->setTitleText("X Axis");
chart->addAxis(axisX, Qt::AlignBottom);
QValueAxis *axisY = new QValueAxis;
axisY->setRange(0, 10);
axisY->setLabelFormat("%.2f");
axisY->setTitleText("Y Axis");
chart->addAxis(axisY, Qt::AlignLeft);
series->attachAxis(axisX);
series->attachAxis(axisY);
```
6. 显示QChartView:
```
chartView->show();
```
完整的示例代码如下所示:
```
#include <QApplication>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include <QtCharts/QValueAxis>
QT_CHARTS_USE_NAMESPACE
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QChart *chart = new QChart();
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
QLineSeries *series = new QLineSeries();
series->append(0, 6);
series->append(2, 4);
series->append(3, 8);
series->append(7, 4);
series->append(10, 5);
chart->addSeries(series);
QValueAxis *axisX = new QValueAxis;
axisX->setRange(0, 10);
axisX->setLabelFormat("%.0f");
axisX->setTitleText("X Axis");
chart->addAxis(axisX, Qt::AlignBottom);
QValueAxis *axisY = new QValueAxis;
axisY->setRange(0, 10);
axisY->setLabelFormat("%.2f");
axisY->setTitleText("Y Axis");
chart->addAxis(axisY, Qt::AlignLeft);
series->attachAxis(axisX);
series->attachAxis(axisY);
chartView->show();
return a.exec();
}
```
阅读全文