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

边栏推荐
- Speed regulation and stroke control based on Ti drv8424 driving stepper motor
- CentOS 7使用yum安装PHP7.0
- 不是你脑子不好用,而是因为你没有找到对的工具
- 千万不要把笔记视频乱放!
- Crossing pie · pie pan + Mountain duck = local data management
- Send you through the data cloud
- libpng12.so.0: cannot open shared object file: No such file or directory 亲测有效
- 【考研高数 武忠祥+880版 自用】高数第二章基础阶段思维导图
- [excel] column operation, which performs specific column for data in a cell, such as text division by comma, colon, space, etc
- Trust guessing numbers game
猜你喜欢

scope 数据导出mat

Simple implementation of database connection pool

多表操作-外键级联操作
![[QT] QT after addition, subtraction, multiplication and division, two decimal places are reserved](/img/30/c802ae9b65601832bf52e760e9962d.png)
[QT] QT after addition, subtraction, multiplication and division, two decimal places are reserved

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

Daily code 300 lines learning notes day 11

【QT】qt加减乘除之后,保留小数点后两位

Huluer app help

【笔记】电商订单数据分析实战

葫芦儿 APP 使用帮助
随机推荐
Data governance: data governance framework (Part I)
Educational administration management system of SSM (free source code)
【问题思考总结】为什么寄存器清零是在用户态进行的?
Leetcode top 100 question 2 Add two numbers
数据治理:数据治理框架(第一篇)
基于TI DRV8424驱动步进电机实现调速和行程控制
芯片,建立在沙粒上的帝国!
SSGSSRCSR区别
论文学习记录随笔 多标签之LSML
SSM的教务管理系统(免费源码获取)
轩逸保养手册
2/15 (awk, awk conditions, awk processing design can perform additional tasks, and use awk array +for loop to realize advanced search)
It's not that you have a bad mind, but that you haven't found the right tool
Summary of common components of applet
This is the necessary software for college students 𞓜 knowledge management
不是你脑子不好用,而是因为你没有找到对的工具
tese_Time_2h
2022.6.30-----leetcode. one thousand one hundred and seventy-five
OpenGL ES: (1) OpenGL ES的由来 (转)
Simple implementation of database connection pool