yhkylin-backup-tools/kybackup/component/mylabel.cpp

108 lines
2.6 KiB
C++
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "mylabel.h"
#include <QPalette>
#include <QFont>
#include <QFontMetrics>
#include <QPainter>
/**
* @brief 通用构造Label方法
* @param parent
*/
MyLabel::MyLabel(QWidget* parent) :
QLabel(parent)
{
}
/**
* @brief 构造固定大小、颜色、内容居中等的label一般用于label控件不会变化重绘的场景
* @param text
* @param parent
* @param color
*/
MyLabel::MyLabel(const QString& text, QWidget* parent /*= nullptr*/, QColor color /*= QColor(0xCC, 0xCC, 0xCC)*/) :
QLabel(parent),
m_text(text)
{
QPalette palette = this->palette();
palette.setColor(QPalette::WindowText, color);
this->setPalette(palette);
this->setAlignment(Qt::AlignCenter);
this->setScaledContents(true);
this->setText(text);
}
MyLabel::~MyLabel()
{}
void MyLabel::setFontColor(QColor color)
{
QPalette palette = this->palette();
palette.setColor(QPalette::WindowText, color);
this->setPalette(palette);
}
void MyLabel::setFontSize(int size)
{
QFont font = this->font();
font.setPixelSize(size);
// 默认为大字体粗体显示
if (size > 20)
font.setBold(true);
this->setFont(font);
}
/**
* @brief 设置字体是否自动换行展示
* @param on
* @note 一般用于setGeometry固定label位置和大小的场景
*/
void MyLabel::setFontWordWrap(bool on)
{
m_bWordWrap = on;
setWordWrap(on);
m_width = this->width();
m_height = this->height();
m_rect = geometry();
}
void MyLabel::paintEvent(QPaintEvent *event)
{
// 1、场景一布局动态变化场景使用原始的QLabel绘制
if (m_isOriginal) {
this->setText(m_text);
QLabel::paintEvent(event);
return ;
}
// 2、场景二setGeometry固定label位置和大小的场景
QFontMetrics fontMetrics(this->font());
int fontSize = fontMetrics.width(m_text);
if (m_bWordWrap && m_width > 0) {
// resize(m_width, m_height);
// setGeometry(m_rect);
// 恢复控件宽度,如果不固定宽度则换行位置不好控制
this->setFixedWidth(m_width);
}
if (fontSize > this->width()) {
if (m_bWordWrap) {
// 调整控件大小
adjustSize();
setAlignment(Qt::AlignTop | Qt::AlignLeft);
this->setText(m_text);
} else {
this->setText(fontMetrics.elidedText(m_text, Qt::ElideRight, this->width()));
}
} else {
if (m_bWordWrap) {
// 恢复控件大小及位置
setGeometry(m_rect);
setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
}
this->setText(m_text);
}
QLabel::paintEvent(event);
}