在QT下开发虚拟示波器程序时,需要用到曲线显示控件,开源的有QCustomPlot和QWT,其中QCustomPlot可以直接利用其源码,而不需要使用链接库的方式,因此,得到了大量的应用,为了简化,我使用了QCustomPlot 1.3.0的源代码并进行了修改实现完整的功能。
1、X轴和Y轴坐标迹线
常见示波器上,可以设置X轴和Y轴坐标迹线并且可以移动。为此,在借鉴网上代码(http://www.manongjc.com/article/22306.html 基于QCustomPlot绘图,鼠标跟随动态显示曲线上的点的值)基础上,定义ScopeTraceLine类,与网上提供代码相比,增加了代表位置的坐标值变量和获取属性函数,并做出了相应的修改。
///
/// \brief The ScopeCrossLine class:用于显示鼠标移动过程中的鼠标位置的直线
///
class ScopeTraceLine : public QObject
{
public:
explicit ScopeTraceLine(QCustomPlot *_plot, LineType _type = VerticalLine, QObject *parent = Q_NULLPTR);
~ScopeTraceLine();
void initLine();
void updatePosition(double xValue, double yValue);
void setSelected(bool selected);
void setVisible(bool vis);
LineType GetType()const{return m_type;}
double getPositionX()const{return m_xValue;}
double getPositionY()const{return m_yValue;}
protected:
bool m_visible;//是否可见
LineType m_type;//类型
QCustomPlot *m_plot;//图表
QCPItemStraightLine *m_lineV; //垂直线
QCPItemStraightLine *m_lineH; //水平线
double m_xValue;
double m_yValue;
};
具体实现函数如下:
ScopeTraceLine::ScopeTraceLine(QCustomPlot *_plot, LineType _type, QObject *parent)
: QObject(parent),
m_type(_type),
m_plot(_plot)
{
m_lineV = Q_NULLPTR;
m_lineH = Q_NULLPTR;
m_xValue= -999;
m_yValue= -999;
initLine();
}
ScopeTraceLine::~ScopeTraceLine()
{
if(m_plot)
{
if (m_lineV)
m_plot->removeItem(m_lineV);
if (m_lineH)
m_plot->removeItem(m_lineH);
}
}
void ScopeTraceLine::initLine()
{
if(m_plot)
{
QPen linesPen(Qt::green, 1, Qt::DashLine);
if(VerticalLine == m_type || Both == m_type)
{
m_lineV = new QCPItemStraightLine(m_plot);//垂直线
m_lineV->setLayer("overlay");
m_lineV->setPen(linesPen);
m_lineV->setClipToAxisRect(true);
m_lineV->point1->setCoords(0, 0);
m_lineV->point2->setCoords(0, 0);
}
if(HorizonLine == m_type || Both == m_type)
{
m_lineH = new QCPItemStraightLine(m_plot);//水平线
m_lineH->setLayer("overlay");
m_lineH->setPen(linesPen);
m_lineH->setClipToAxisRect(true);
m_lineH->point1->setCoords(0, 0);
m_lineH->point2->setCoords(0, 0);
}
}
}
void ScopeTraceLine::setVisible(bool vis)
{
if(m_lineV)
m_lineV->setVisible(vis);
if(m_lineH)
m_lineH->setVisible(vis);
}
void ScopeTraceLine::setSelected(bool selected)
{
QPen linesPen(Qt::green, 1, Qt::DashLine);
if(selected)
linesPen.setColor(Qt::red);
if(VerticalLine == m_type || Both == m_type)
{