当前位置:网站首页>QT write custom control - self drawn battery
QT write custom control - self drawn battery
2022-07-01 05:46:00 【my_ angle2016】
Complete code
battery.h
#ifndef BATTERY_H
#define BATTERY_H
#include <QMainWindow>
class Battery : public QMainWindow
{
Q_OBJECT
public:
Battery(QWidget *parent = nullptr);
~Battery();
void SetValue(int currentValue);
int GetValue();
protected:
void paintEvent(QPaintEvent *);
void drawBorder(QPainter *painter);
void drawBg(QPainter *painter);
void drawText(QPainter *painter);
private slots:
void inputValue();
private:
double _currentValue;
int _margin;
double _minValue; // minimum value
double _maxValue; // Maximum
bool _isForward; // Move forward or not
int _batteryWidth;
int _batteryHeight;
QRectF batteryRect; // Battery body area
QTimer *inputTimer; // Draw the timer
};
#endif // BATTERY_H
battery.cpp
#pragma execution_character_set("utf-8")
#include "battery.h"
#include "qpainter.h"
#include "qtimer.h"
#include "qdebug.h"
Battery::Battery(QWidget *parent)
: QMainWindow(parent)
, _currentValue(10)
, _margin(3)
, _minValue(0)
, _maxValue(100)
, _isForward(true)
, _batteryWidth(50)
, _batteryHeight(20)
{
// ui->setupUi(this); // drive UI The designer
// setFixedSize(300, 180); // Fixed size
setBaseSize(350, 180);
///-- Set a timer , cycle 10ms , The input values inputValue()
inputTimer = new QTimer(this);
inputTimer->setInterval(100);
connect(inputTimer, SIGNAL(timeout()), this, SLOT(inputValue())); // timing 100ms call 1 Time inputValue
inputTimer->start();
}
Battery::~Battery()
{
if (inputTimer->isActive()) {
inputTimer->stop();
}
}
void Battery::SetValue(int currentValue)
{
_currentValue = currentValue;
}
int Battery::GetValue()
{
return _currentValue;
}
///--1. Draw the event
/* Called whenever the widget needs to be redrawn , Each widget to display output must implement it .
This event handler can be reimplemented in subclasses to receive drawing events . It can be repaint() or update() Result .
Many widgets when they are requested , They simply redraw the entire interface , But some widgets draw only the requested area QPaintEvent::region() To optimize , for example ,QListView and QCanvas That's what it does .
Link to the original text :https://blog.csdn.net/u012151242/article/details/78947024
*/
void Battery::paintEvent(QPaintEvent *)
{
// Drawing preparation , Enable anti aliasing
QPainter painter(this);
painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
///--1.1 Draw borders and headers
drawBorder(&painter);
///--1.2 Draw fill
drawBg(&painter);
///--1.3 Internal percentage
drawText(&painter);
}
///--1.1 Draw borders and headers
void Battery::drawBorder(QPainter *painter)
{
// Save state
painter->save();
// Set the color and thickness of the pen
painter->setPen(QPen(Qt::gray, 5));
// No brush filling
painter->setBrush(Qt::NoBrush);
// Draw the given rounded rectangle rectangular xRadius yRadius
// painter->drawRoundedRect(batteryRect, borderRadius, borderRadius);
// The battery border is centered
batteryRect = QRectF((width()-_batteryWidth)/2, (height()-_batteryHeight)/2, _batteryWidth, _batteryHeight);
painter->drawRoundedRect(batteryRect, 2, 2);
// Battery head : Draw a straight line
painter->setPen(QPen(Qt::gray, 5));
QLineF line(batteryRect.topRight().x()+5, batteryRect.topRight().y()+5, batteryRect.topRight().x()+5, batteryRect.bottomRight().y()-5);
painter->drawLine(line);
// Reply to saved status
painter->restore();
}
///--1.2 Draw fill
void Battery::drawBg(QPainter *painter)
{
painter->save();
// Determine brush color
if(_currentValue<=10) {
painter->setBrush(QColor(204, 38, 38)); // red
}
else if (_currentValue <= 20) {
painter->setBrush(QColor(198, 163, 0)); // yellow
}
else {
painter->setBrush(QColor(50, 205, 51)); // green
}
// The current power is converted to wide
double width = _currentValue * (batteryRect.width() - (_margin * 2)) / 100;
// Locate the upper left corner
QPointF topLeft(batteryRect.topLeft().x() + _margin, batteryRect.topLeft().y() + _margin);
// Identify the lower right corner of the change , At least give me 10, Show the internal fill
QPointF bottomRight(batteryRect.topLeft().x() + width + _margin, batteryRect.bottomRight().y() - _margin);
QRectF rect(topLeft, bottomRight);
// No line width
painter->setPen(Qt::NoPen);
painter->drawRoundedRect(rect, 5, 5);
painter->restore();
}
///--1.3 Internal percentage
void Battery::drawText(QPainter *painter) {
painter->save();
painter->setPen(Qt::black);
painter->setFont(QFont("Arial",11));
QString value = QString::number(_currentValue) + "%";
// A good way to center text
painter->drawText(batteryRect,Qt::AlignCenter,value);
painter->restore();
}
//1. drive 、 Input
void Battery::inputValue()
{
/* if(_isForward) _currentValue += 1;
else _currentValue -= 1;
if(_currentValue >= 45) {
_currentValue = 45;
_isForward = false;
}
if(_currentValue <= _minValue) {
_currentValue = _minValue;
_isForward = true;
}*/
_currentValue = GetValue();
if(_currentValue >= 100) {
_currentValue = 100;
_isForward = false;
}
if(_currentValue <= _minValue) {
_currentValue = _minValue;
_isForward = true;
}
// Repaint , Will call paintEvent() function
this->update();
}
Call the process
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include "battery.h"
Battery *battery;
int g_currentValue = 10;
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
battery = new Battery();
battery->setGeometry(rect().x()+500, rect().y()+10,
400, 300);
battery->setParent(this);
inputTimer = new QTimer(this);
inputTimer->setInterval(100);
connect(inputTimer, SIGNAL(timeout()), this, SLOT(inputValue())); // timing 100ms call 1 Time inputValue
inputTimer->start();
}
Widget::~Widget()
{
delete ui;
}
void Widget::inputValue()
{
if(g_currentValue <=0)
g_currentValue = 100;
else
g_currentValue -=1;
battery->SetValue(g_currentValue);
}Screenshot of operation effect

边栏推荐
- 表格中el-tooltip 实现换行展示
- 穿越派·派盘 + 思源笔记 = 私人笔记本
- Don't put your notes and videos everywhere!
- vsCode函数注解/文件头部注解快捷键
- Geoffrey Hinton:我的五十年深度学习生涯与研究心法
- libpng12.so.0: cannot open shared object file: No such file or directory 亲测有效
- Beauty of Mathematics - Application of Mathematics
- 导数的左右极限和左右导数的辨析
- On the first day of the new year, 3000 Apache servers went down
- 论文学习记录随笔 多标签之LSML
猜你喜欢

OpenGL ES: (5) OpenGL的基本概念、OpenGL ES 在屏幕产生图片的过程、OpenGL管线(pipeline)

芯片,建立在沙粒上的帝国!

Continue to learn MySQL

Simple implementation of database connection pool

He struggled day and night to protect his data

It's not that you have a bad mind, but that you haven't found the right tool

boot+jsp的高校社团管理系统(附源码下载链接)

On the first day of the new year, 3000 Apache servers went down

Mongodb学习篇:安装后的入门第一课

Boot + jsp University Community Management System (with source Download Link)
随机推荐
2022.6.30-----leetcode.1175
Orcle创建用户+角色
Fiber Bragg grating (FBG) notes [1]: waveguide structure and Bragg wavelength derivation
Crossing pie · pie pan + Mountain duck = local data management
vsCode函数注解/文件头部注解快捷键
OpenGL ES: (2) OpenGL ES 与 EGL、GLSL的关系
SSM的教务管理系统(免费源码获取)
boot+jsp的高校社團管理系統(附源碼下載鏈接)
亲爱的派盘用户,我要向您表白!
Through cooperation with the University of international trade, we can increase efficiency for college students
新手在挖财开通证券账户安全吗?
数据库连接池的简单实现
Web Security (IX) what is JWT?
Beauty of Mathematics - Application of Mathematics
喊我们大学生个人云服务特供商
Brief description of activation function
What is the at instruction set often used in the development of IOT devices?
从诺奖知“边缘计算”的未来!
[SRS] use of Vhost isolated stream: push / pull Stream Address
HDU - 1069 Monkey and Banana(DP+LIS)