当前位置:网站首页>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

边栏推荐
- Educational administration management system of SSM (free source code)
- 【考研高数 武忠祥+880版 自用】高数第二章基础阶段思维导图
- Mongodb學習篇:安裝後的入門第一課
- 多表操作-外键级联操作
- boot+jsp的高校社團管理系統(附源碼下載鏈接)
- Summary of common components of applet
- College community management system based on boot+jsp (with source code download link)
- 从诺奖知“边缘计算”的未来!
- [ffmpeg] [reprint] image mosaic: picture in picture with wheat
- Continuous breakthrough and steady progress -- Review and Prospect of cross platform development technology of mobile terminal
猜你喜欢

为什么用葫芦儿派盘取代U盘?

【医学分割】u2net

导数的左右极限和左右导数的辨析

Daily code 300 lines learning notes day 11

教务管理系统(免费源码获取)

In depth understanding of condition source code interpretation and analysis of concurrent programming

Multi table operation - foreign key cascade operation

从诺奖知“边缘计算”的未来!

College community management system based on boot+jsp (with source code download link)

表格中el-tooltip 实现换行展示
随机推荐
College community management system based on boot+jsp (with source code download link)
It's not that you have a bad mind, but that you haven't found the right tool
论文学习记录随笔 多标签之LSML
Data governance: data governance management (Part V)
Brief description of activation function
Enter an expression (expressed as a string) and find the value of this expression.
C语言初阶——实现扫雷游戏
Why use huluer pie disk instead of U disk?
excel高级绘图技巧100讲(一)-用甘特图来展示项目进度情况
4GB大文件,如何实时远程传输和共享?
Educational administration management system of SSM (free source code)
数据库连接池的简单实现
扩展点系列之SmartInstantiationAwareBeanPostProcessor确定执行哪一个构造方法 - 第432篇
数据治理:元数据管理实施(第四篇)
HCM 初学 ( 二 ) - 信息类型
喊我们大学生个人云服务特供商
boot+jsp的高校社团管理系统(附源码下载链接)
JDBC常见面试题
Ssm+mysql second-hand trading website (thesis + source code access link)
这才是大学生必备软件 | 知识管理