Qt5_在QWidget中画动态图()转
在以前的文章中,我们介绍了如何在QTabWidget中画网络拓扑图。今天,我们介绍一下,如何使得所画的图呈现出动态的变化,比如在网络拓扑中,随着时间的变化,一些节点显示红色,一些节点显示绿色。
准备过程:红色和绿色的图片
思路:依旧使用重写paintevent函数来实现画图功能,要使图片随着时间的变化更新,就需要使用计时器来触发页面更新,页面更新可以使用update函数。
代码:
#include "showtopology.h" #include "mainwindow.h" #include <QPainter> #include <QWidget> #include <QTime> #include <QTimer> showtopology::showtopology(QWidget *parent) : QWidget(parent) { QTimer *timer3= new QTimer();//声明计时器 connect(timer3,SIGNAL(timeout()),this,SLOT(update()));//计时器用来触发更新 timer3->start(1000);//更新间隔为1秒 } void showtopology::paintEvent(QPaintEvent *event) { QPainter paint(this); paint.setPen(Qt::DashLine); paint.setRenderHint(QPainter::Antialiasing, true); QPixmap ap1("ap1.png");//AP和两种STA的图片的声明; QPixmap img1("STA2.png"); QPixmap img2("STA1.png"); paint.drawPixmap(350,150,ap1); qsrand(time(NULL)); int n1; double n[50];//一共有50个节点 for (int i =0; i<50; i++) { n1= qrand(); n[i] = n1/10000000.0; } for(int i = 0; i<50; i++) { if (n[i]<30)//使某一个节点的随机数小于30的显示STA2的图片 { switch (i) { case 0 :paint.drawPixmap(50,20,img1); break; case 1: paint.drawPixmap(100,100,img1); break; case 2: paint.drawPixmap(350,200,img1); break; case 3: paint.drawPixmap(500,200,img1); break; case 4 :paint.drawPixmap(300,75,img1); break; case 5 :paint.drawPixmap(503,120,img1); break; case 6 :paint.drawPixmap(160,66,img1); break; case 7 :paint.drawPixmap(200,190,img1); break; case 8: paint.drawPixmap(360,190,img1); break; case 9 :paint.drawPixmap(350,180,img1); break; default : break; } paint.drawLine(350,150,50,20); paint.drawLine(350,150,100,100); paint.drawLine(350,150,350,200); paint.drawLine(350,150,500,200); paint.drawLine(350,150,300,75); paint.drawLine(350,150,503,120); paint.drawLine(350,150,160,66); paint.drawLine(350,150,200,190); paint.drawLine(350,150,360,190); paint.drawLine(350,150,350,180); } else//节点随机数大于30的显示STA1的图片 { switch (i) { case 0 :paint.drawPixmap(50,20,img2);//画STA break; case 1: paint.drawPixmap(100,100,img2); break; case 2: paint.drawPixmap(350,200,img2); break; case 3: paint.drawPixmap(500,200,img2); break; case 4 :paint.drawPixmap(300,75,img2); break; case 5 :paint.drawPixmap(503,120,img2); break; case 6 :paint.drawPixmap(160,66,img2); break; case 7 :paint.drawPixmap(200,190,img2); break; case 8: paint.drawPixmap(360,190,img2); break; case 9 :paint.drawPixmap(350,180,img2); break; default : break; } paint.drawLine(350,150,50,20);//画连接线 paint.drawLine(350,150,100,100); paint.drawLine(350,150,350,200); paint.drawLine(350,150,500,200); paint.drawLine(350,150,300,75); paint.drawLine(350,150,503,120); paint.drawLine(350,150,160,66); paint.drawLine(350,150,200,190); paint.drawLine(350,150,360,190); paint.drawLine(350,150,350,180); } } }
最终的效果如下图所示:
————————————————
版权声明:本文为CSDN博主「caoyangxiaoyao」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/caoyangxiaoyao/article/details/69261265