本文主要是介绍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);//画STAbreak;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);}}
}
最终的效果如下图所示:
这篇关于Qt5_在QWidget中画动态图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!