Qt Charts——QChartsView
1、新建一个继承自QChartView的类,在其构造函数中加入如下代码
1 QSplineSeries *series1 = new QSplineSeries();//曲线 2 *series1 << QPointF(1, 3) << QPointF(3, 4) << QPointF(7, 3)<< QPointF(12, 3)<< QPointF(16, 4) ; 3 4 QChart *chart = new QChart(); 5 chart->addSeries(series); 6 chart->setTitle("QChartView"); 7 chart->createDefaultAxes(); 8 chart->axisX()->setRange(0, 20); 9 chart->axisY()->setRange(0, 10); 10 11 setRenderHint(QPainter::Antialiasing); 12 setChart(chart); //将曲线图加到QChartView中
QChartView是一个可以显示图表的独立小控件。
2、继承自QChartView的类可以重写 鼠标移动和鼠标点击事件
1 void ChartView::mouseMoveEvent(QMouseEvent *event) 2 {//在鼠标所在位置划线 3 chart->remove(series2); 4 chart->remove(series3); 5 m_x=chart->mapToValue(event->pos.x()).x(); 6 m_y=chart->mapToValue(event->pos.y()).y(); 7 8 series2 = new QSplineSeries(); 9 *series2<<QPoint(m_x, 0)<<QPoint(m_x, 20); 10 chart->addSeries(series2); 11 series3 = new QSplineSeries(); 12 *series3<<QPoint(0, m_y)<<QPoint(10, m_y); 13 chart->addSeries(series3); 14 }
如果不是继承自QChartView,而是采用组合的设计模式,鼠标移动事件无法生效。