1、在pro文件中添加QT += charts。
2、在头文件中添加#include <QtCharts/QtCharts>
3、在界面使用Qt Creator添加一个QGraphicsView组件,然后提升为QChartView。
提升的时候,这样写提升为的类:QtCharts::QChartView,头文件写:qchartview.h。
截图.png
如果没有对QGraphicsView提升,可能会导致在QGraphicsView中添加的Chart不显示;若用QChartView显示Chart则不受此限制(会单独生成一个独立窗口显示)。
//QChart负责管理数据
//QChartView负责显示
折线图代码:
QLineSeries *series = new QLineSeries();
series->append(0, 6);
series->append(2, 4);
series->append(3, 8);
series->append(7, 4);
series->append(10, 5);
*series << QPointF(11, 1) << QPointF(13, 3) << QPointF(17, 6) << QPointF(18, 3) << QPointF(20, 2);
QChart *chart = new QChart();
chart->legend()->hide();
chart->addSeries(series);
chart->createDefaultAxes();
chart->setTitle("Simple line chart example");
ui->graphicsView->setChart(chart);
ui->graphicsView->setRenderHint(QPainter::Antialiasing);
饼图代码:
QPieSeries *series = new QPieSeries();
series->append("10%", 1);
series->append("20%", 2);
series->append("70%", 7);
series->setLabelsVisible();
QPieSlice *slice_red = series->slices().at(0);
QPieSlice *slice_green = series->slices().at(1);
QPieSlice *slice_blue = series->slices().at(2);
slice_red->setColor(QColor(255,0,0,255));
slice_green->setColor(QColor(0,255,0,255));
slice_blue->setColor(QColor(0,0,255,255));
QChart *chart = new QChart();
chart->addSeries(series);
chart->setTitle("PieChart Example");
chart->legend()->hide();
//QChartView *chartview = new QChartView(chart);
//chartview->setRenderHint(QPainter::Antialiasing);
//chartview->show();
ui->graphicsView->setChart(chart);
ui->graphicsView->setRenderHint(QPainter::Antialiasing);
效果图:
效果图.png
网友评论