Qt界面中绘制WiFi信号强弱图标。模拟类似手机的WIFI强度图标的绘制,比较简单,欢迎参考。
一、简述
使用Qt实现WIFI信号图标。
二、效果
三、核心代码
1、头文件
#ifndef WIFIICON_H
#define WIFIICON_H
#include <QWidget>
class WifiIcon : public QWidget
{
Q_OBJECT
public:
explicit WifiIcon(QWidget *parent = nullptr);
//信号强度
enum wifiStrength{
Zero = 0,
One,
Two,
Three,
Four
};
//设置信号强度
void setStrength(wifiStrength strength);
protected:
void paintEvent(QPaintEvent *);
void drawCircularArc(QPainter *painter, int radius, int startAngle, int angleLength, int arcHeight);
private:
wifiStrength m_wifiStrength;
};
#endif // WIFIICON_H
2、cpp代码
#include "wifiicon.h"
#include <QPainter>
#include <QTimer>
WifiIcon::WifiIcon(QWidget *parent) : QWidget(parent)
{
m_wifiStrength = wifiStrength::Zero;
}
void WifiIcon::paintEvent(QPaintEvent *)
{
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
double Width = width();
double Height = height();
painter.setPen(Qt::SolidLine);
int minWidHei;
if(Height>Width){
minWidHei=Width;
}else{
minWidHei=Height;
}
double radius_1 = minWidHei/9.5;
double radius_2 = Height*0.85;
int arcHeight = Height/10.5;
QColor havaSignal = Qt::white;
QColor noSignal = QColor(100,100,100);
int splitValue=0;
switch(m_wifiStrength)
{
case WifiIcon::Four:
splitValue=4;
break;
case WifiIcon::Three:
splitValue=3;
break;
case WifiIcon::Two:
splitValue=2;
break;
case WifiIcon::One:
splitValue=1;
break;
default:
break;
};
for(int i=1;i<5;i++){
if(i<=splitValue&&splitValue!=0){
painter.setBrush(havaSignal);
painter.setPen(havaSignal);
}else{
painter.setBrush(noSignal);
painter.setPen(noSignal);
}
switch (i) {
case 1:
painter.drawEllipse(QPointF(Width*0.5,Height*0.88),radius_1,radius_1);
painter.translate(QPointF(Width*0.5,Height*0.9));
break;
case 2:
drawCircularArc(&painter, radius_2*0.40,45,90, arcHeight);
break;
case 3:
drawCircularArc(&painter, radius_2*0.70,45,90, arcHeight);
break;
case 4:
drawCircularArc(&painter, radius_2, 45,90, arcHeight);
break;
}
}
}
void WifiIcon::drawCircularArc(QPainter *painter, int radius, int startAngle, int angleLength, int arcHeight)
{
QRectF rect(-radius, -radius, radius<<1, radius<<1);
QPainterPath path;
path.arcTo(rect, startAngle, angleLength);
QPainterPath subPath;
subPath.addEllipse(rect.adjusted(arcHeight, arcHeight, -arcHeight, -arcHeight));
path -= subPath;
painter->drawPath(path);
}
void WifiIcon::setStrength(wifiStrength strength)
{
m_wifiStrength = strength;
update();
}