QtChart 官方手册:https://doc.qt.io/qt-5/qtcharts-index.html
或者直接看Qt软件帮助手册
折线图使用: QLineSeries类
- QLineSeries* series = new QLineSeries();
- series->append(0, 6);
- series->append(2, 4);
- ...
- chart->addSeries(series);
样条图使用:QSplineSeries Class
- QSplineSeries* series = new QSplineSeries();
- series->append(0, 6);
- series->append(2, 4);
- ...
- chart->addSeries(series);
感觉不会常用,不深入研究
Qt主要支持五种轴类型:
QAbstractAxis class : 用于刻度线轴
QValueAxis class : 数据轴,常用
- QChartView *chartView = new QChartView;
- QLineSeries *series = new QLineSeries;
- // ...
- chartView->chart()->addSeries(series);
-
- QValueAxis *axisX = new QValueAxis;
- axisX->setRange(10, 20.5);
- axisX->setTickCount(10);
- axisX->setLabelFormat("%.2f");
- chartView->chart()->setAxisX(axisX, series);
其他感觉不常用,不深入研究
效果如下:
- QLineSeries *series = new QLineSeries();
- for (int i = 0; i < 500; i++) {
- QPointF p((qreal) i, qSin(M_PI / 50 * i) * 100);
- p.ry() += qrand() % 20;
- *series << p;
- }
-
- Chart *chart = new Chart();
- chart->addSeries(series);
- chart->setTitle("Zoom in/out example");
- chart->setAnimationOptions(QChart::SeriesAnimations);
- chart->legend()->hide();
- chart->createDefaultAxes();
-
- ChartView *chartView = new ChartView(chart);
- chartView->setRenderHint(QPainter::Antialiasing);
-
- QMainWindow window;
- window.setCentralWidget(chartView);
- window.resize(400, 300);
- window.grabGesture(Qt::PanGesture);
- window.grabGesture(Qt::PinchGesture);
- window.show();
重写鼠标按键相关函数
- protected:
- bool viewportEvent(QEvent *event);
- void mousePressEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void mouseReleaseEvent(QMouseEvent *event);
- void keyPressEvent(QKeyEvent *event);
按键操作
关键在于zoomIn()/zoomOut()函数调用
- void ChartView::keyPressEvent(QKeyEvent *event)
- {
- switch (event->key()) {
- case Qt::Key_Plus:
- chart()->zoomIn();
- break;
- case Qt::Key_Minus:
- chart()->zoomOut();
- break;
- case Qt::Key_Left:
- chart()->scroll(-10, 0);
- break;
- case Qt::Key_Right:
- chart()->scroll(10, 0);
- break;
- case Qt::Key_Up:
- chart()->scroll(0, 10);
- break;
- case Qt::Key_Down:
- chart()->scroll(0, -10);
- break;
- default:
- QGraphicsView::keyPressEvent(event);
- break;
- }
- }
- bool Chart::sceneEvent(QEvent *event)
- {
- if (event->type() == QEvent::Gesture)
- return gestureEvent(static_cast
(event)); - return QChart::event(event);
- }
-
- bool Chart::gestureEvent(QGestureEvent *event)
- {
- if (QGesture *gesture = event->gesture(Qt::PanGesture)) {
- QPanGesture *pan = static_cast
(gesture); - QChart::scroll(-(pan->delta().x()), pan->delta().y());
- }
-
- if (QGesture *gesture = event->gesture(Qt::PinchGesture)) {
- QPinchGesture *pinch = static_cast
(gesture); - if (pinch->changeFlags() & QPinchGesture::ScaleFactorChanged)
- QChart::zoom(pinch->scaleFactor());
- }
-
- return true;
- }
主要调用QChart类两个函数