赞
踩
效果图
QWidget自定义信号强度显示控件,比较简单,适合初学者。
主要就是继承于QWidget, 重写paintEvent以绘制;
源码如下:
signalwidget.h
#ifndef SIGNALWIDGET_H #define SIGNALWIDGET_H /*! 信号显示控件 自适应长宽比例; widget 高度分为4份,信号柱由低到高使用对应份额; widget 宽度分为十份,四个信号柱各占一份,三个空白区域各占两份 作者(csdn):为啥不吃肉捏 */ #include <QWidget> class SignalWidget : public QWidget { Q_OBJECT public: explicit SignalWidget(QWidget *parent = nullptr); /*! 信号强度 */ enum class SignalStrength{ Zero, One, Two, Three, Four }; /*! 设置信号强度 */ void setSignalStrength(SignalStrength newSignalStrength); protected: void paintEvent(QPaintEvent *event) override; private: SignalStrength m_signalStrength; }; #endif // SIGNALWIDGET_H
signalwidget.cpp
#include "signalwidget.h" #include <QPainter> SignalWidget::SignalWidget(QWidget *parent) : QWidget(parent) { } void SignalWidget::paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter p(this); p.setRenderHint(QPainter::Antialiasing); //widget 高度分为4份,信号柱由低到高使用对应份额 float hUnit = this->height() / 4.0; int h1 = hUnit * 1; int h2 = hUnit * 2; int h3 = hUnit * 3; int h4 = hUnit * 4; //widget 宽度分为十份,四个信号柱各占一份,三个空白区域各占两份 float wUnit = this->width() / 10.0; int x1 = 1; int x2 = wUnit * 3; int x3 = wUnit * 6; int x4 = wUnit * 9 - 1; //border-radius int rounded = wUnit / 2.0; QColor havaSignal = QColor(79, 134, 210); QColor noSignal = Qt::gray; QColor colorOne, colorTwo, colorThree, colorFour; colorOne = noSignal; colorTwo = noSignal; colorThree = noSignal; colorFour = noSignal; switch(m_signalStrength) { case SignalStrength::Four: colorFour = havaSignal; case SignalStrength::Three: colorThree = havaSignal; case SignalStrength::Two: colorTwo = havaSignal; case SignalStrength::One: colorOne = havaSignal; default: break; }; p.setPen(colorOne); p.setBrush(colorOne); p.drawRoundedRect(x1, this->height() - h1, wUnit, h1, rounded, rounded); p.setPen(colorTwo); p.setBrush(colorTwo); p.drawRoundedRect(x2, this->height() - h2, wUnit, h2, rounded, rounded); p.setPen(colorThree); p.setBrush(colorThree); p.drawRoundedRect(x3, this->height() - h3, wUnit, h3, rounded, rounded); p.setPen(colorFour); p.setBrush(colorFour); p.drawRoundedRect(x4, this->height() - h4, wUnit, h4, rounded, rounded); } void SignalWidget::setSignalStrength(SignalStrength newSignalStrength) { m_signalStrength = newSignalStrength; this->update(); }
使用:
我们在 ui 设计器中拖出一个widget或者在工程中 new 一个SignalWidget,在此我们使用比较快速的方式,在ui中拖出widget,并提升为 SignalWidget,然后如下设置:
ui->widget->setSignalStrength(SignalWidget::SignalStrength::Three);
运行如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。