QCustomPlot实现极坐标图——QtWidgets

前言

前面用QtChart实现了极坐标图,感觉不是很方便,特别是一些点的图形,一般需要自己绘制,而QCustomPlot自带挺多的;还有极坐标的角度轴(即 圆圈),相比起来,QCustomPlot更为清晰。

QtChart 与 QCustomPlot各方面对比

Qwt、QChart、QCustomPlot使用_qcustomplot qwt_mahuifa的博客-CSDN博客

这个博客里面写的很好,美观、使用、性能方面都进行了对比。

资源地址和版本 

QCustomPlot的下载地址:Qt Plotting Widget QCustomPlot - Download

版本: Version 2.1.0 released on 29.03.21

准备工作

我是下载最大的那个,里面还有源码、示例还有帮助文档,帮助文档还可以加在Qt的帮助文档中使用,只要将 qcustomplot\documentation\qcustomplot.qch 放到Qt的安装目录 Qt5.xx.x\Docs\Qt-5.xx.x中,Qt就可以在自动识别出来。

我是直接将qcustomplot.cpp文件和qcustomplot.h文件直接加到项目中的,不过还要在pro文件里加 库 printsupport ,QCustomPlot里面用到了。

QT += printsupport

说明和代码

QCustomPlot使用更为简单,大概分为三部分:

:一般的视图自带 x1y1轴和x2y2轴。不过极坐标轴跟平时的不一样,用QCPPolarAxisAngular

线图(数据):常见的折线图之类的是CPGraph,一般使用函数addGraph创建对象,它创建后,是保存在容器QList里的,故可根据索引获取,如下;不过极坐标图用的是QCPPolarGraph,它也需要重新设置。

  customPlot->addGraph();
  customPlot->graph(0)->setPen(QPen(Qt::blue));

视图:即QCustomPlot,它继承的是QWidget,所以可以在QtDesigner上将QWidget提升为QCustomPlot。

对了,有一点是,在QCustomPlot自带的极坐标示例代码中,有一句话

// Warning: Polar plots are a still a tech preview

他只是一个预览,还不成熟,所以在实际项目中,可能会出现问题。

代码如下,和我之前用QtChart写的极坐标相似。

void FirstCustomPlot::polarPlotDemo()
{
    ui->qcustomplot->plotLayout()->clear();
    QCPPolarAxisAngular* angularAxis=new QCPPolarAxisAngular(ui->qcustomplot);
    ui->qcustomplot->plotLayout()->addElement(0,0,angularAxis);
    ui->qcustomplot->setInteractions(QCP::iRangeDrag|QCP::iRangeZoom);
    angularAxis->setRangeDrag(false);
    angularAxis->setTickLabelMode(QCPPolarAxisAngular::lmUpright);
    angularAxis->radialAxis()->setTickLabelRotation(0);
    angularAxis->radialAxis()->setAngle(45);

    angularAxis->grid()->setAngularPen(QPen(QColor(200,200,200),0,Qt::SolidLine));
    angularAxis->grid()->setSubGridType(QCPPolarGrid::gtAll);

    QCPPolarGraph* g1=new QCPPolarGraph(angularAxis,angularAxis->radialAxis());
    QCPPolarGraph* g2=new QCPPolarGraph(angularAxis,angularAxis->radialAxis());
    g2->setPen(QPen(QColor(255,150,20)));
    g2->setBrush(QColor(255,150,20,50));
    g1->setScatterStyle(QCPScatterStyle::ssStar);
    g1->setPen(QPen(Qt::blue));
//    g1->setLineStyle(QCPPolarGraph::lsNone);
    for(int i=0;i<100;i++){
        g1->addData(i/100.0*360.0,qSin(i/100.0*M_PI*8)*8+1);
        g2->addData(i/100.0*360.0,qSin(i/100.0*M_PI*6)*2);
    }

    angularAxis->setRange(0,360);
    angularAxis->radialAxis()->setRange(-10,10);
}

效果图

 

猜你喜欢

转载自blog.csdn.net/xiaopei_yan/article/details/129993633