2018年06月22日 18:04:34 逸璞丷昊-承接本科畢設、價格私聊 閱讀數:7336更多
所屬專欄: Qt的學習之旅
版權聲明:- - 內容若有錯誤,請您務必指出,感謝讓我提高並給予我建議的你! - - 轉載請註明出處 https://blog.csdn.net/yishuicanhong/article/details/80738361
本來是想寫一篇上位機通過串口接收數據並進行簡單實時動態畫圖的,但是網上關於Qt串口接收數據的博客已經非常多了,且也會導致內容太多,顯得複雜,如果需要串口收發數據例程,網上隨便百度就能收到了,也可以下載我寫的北斗/GPS雙模定位上位機,這裏主要介紹一下收到數據後的畫圖實現。
使用Qt繪製圖形,首先需要了解Qt的窗口與視口的概念,理解Qt的座標變換,然後學會掌握Qpainter這個類的使用就能實現基本的繪圖功能了。下面一個實時繪製曲線圖形的例子(座標用應該直接使用一個Qpoint模板的列表表示比較好)。這裏,實時數據只是由使用creatData函數產生,在實際工程中將數據改爲讀取實時數據即可。
頭文件
-
#ifndef WIDGET_H
-
#define WIDGET_H
-
#include <QWidget>
-
#include <QTimer>
-
#include <QList>
-
class Widget : public QWidget
-
{
-
Q_OBJECT
-
protected:
-
void paintEvent(QPaintEvent *);
-
public:
-
int m_count;
-
float x;
-
QTimer* m_Timer;
-
QList<float> xList;
-
QList<float> yList;
-
Widget(QWidget *parent = 0);
-
~Widget();
-
public slots:
-
void creatData();
-
};
-
#endif // WIDGET_H
源文件
-
#include "Widget.h"
-
#include <QPainter>
-
#include <QPointF>
-
#include <QPen>
-
#include <qmath.h>
-
Widget::Widget(QWidget *parent) : QWidget(parent)
-
{
-
x = -10;
-
m_count = 0;
-
m_Timer = new QTimer(this);
-
m_Timer->start(10);
-
connect(m_Timer,SIGNAL(timeout()),this,SLOT(creatData()));
-
}
-
void Widget::creatData()
-
{
-
x += 0.2;
-
m_count += 1;
-
if(m_count%2)
-
{
-
xList.append(x);
-
yList.append(qSin(x));
-
}
-
else
-
{
-
xList.append(x);
-
yList.append(qSin(x));
-
update();
-
}
-
if(m_count == 100)
-
{
-
xList.clear();
-
yList.clear();
-
m_count = 0;
-
x = -10;
-
}
-
}
-
void Widget::paintEvent(QPaintEvent *)
-
{
-
QPainter painter(this);
-
QPen pen;
-
pen.setColor(Qt::green);
-
pen.setStyle(Qt::SolidLine);
-
pen.setWidthF(0.05);
-
painter.setPen(pen);
-
painter.setViewport(50, 50, width()-100, height()-100);
-
painter.setWindow(-10, 2, 20, -4); // (-10, 2) (10, -2)
-
painter.fillRect(-10, 2, 20, -4, Qt::white);
-
painter.drawLine(QPointF(-10, 0), QPointF(10, 0)); // x
-
painter.drawLine(QPointF(0, 2), QPointF(0, -2)); // y
-
for(int i = 0; i < yList.count(); i++)
-
{
-
if(i == 0)
-
painter.drawPoint(QPointF(xList[i], yList[i]));
-
else
-
painter.drawLine(QPointF(xList[i-1], yList[i-1]), QPointF(xList[i], yList[i]));
-
}
-
}
-
Widget::~Widget()
-
{
-
}
主函數
-
#include <QApplication>
-
#include "Widget.h"
-
int main(int argc, char *argv[])
-
{
-
QApplication a(argc, argv);
-
Widget w;
-
w.show();
-
return a.exec();