85 lines
2.5 KiB
C++
85 lines
2.5 KiB
C++
#include "Text_Shower.h"
|
|
#include <QFontMetrics>
|
|
#include <QPainter>
|
|
#include <algorithm>
|
|
namespace Flex_Qt {
|
|
Text_Shower::Text_Shower(QWidget* parent) : QWidget(parent) {
|
|
setAttribute(Qt::WA_TranslucentBackground);
|
|
// 宽度交给布局,高度最小
|
|
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
|
|
}
|
|
void Text_Shower::set_text(const QString& text) {
|
|
m_text = text;
|
|
updateGeometry(); // 通知布局重新计算
|
|
update();
|
|
}
|
|
void Text_Shower::set_title(const QString& title) {
|
|
m_title = title;
|
|
updateGeometry();
|
|
update();
|
|
}
|
|
void Text_Shower::set_max_width(int w) {
|
|
m_max_width = w;
|
|
updateGeometry();
|
|
}
|
|
bool Text_Shower::hasHeightForWidth() const {
|
|
return true;
|
|
}
|
|
int Text_Shower::heightForWidth(int width) const {
|
|
width = std::min(width, m_max_width);
|
|
return calculate_height(width);
|
|
}
|
|
QSize Text_Shower::sizeHint() const {
|
|
int w = std::min(400, m_max_width);
|
|
return QSize(w, calculate_height(w));
|
|
}
|
|
QSize Text_Shower::minimumSizeHint() const {
|
|
return QSize(120, 40);
|
|
}
|
|
int Text_Shower::calculate_height(int width) const {
|
|
QFontMetrics fm(font());
|
|
int content_width = width - m_padding * 2;
|
|
if (content_width <= 0)
|
|
return 40;
|
|
QRect text_rect = fm.boundingRect(
|
|
QRect(0, 0, content_width, 10000),
|
|
Qt::TextWordWrap,
|
|
m_text);
|
|
int height = text_rect.height();
|
|
if (!m_title.isEmpty()) {
|
|
QFont title_font = font();
|
|
title_font.setBold(true);
|
|
QFontMetrics title_fm(title_font);
|
|
height += title_fm.height() + 6;
|
|
}
|
|
height += m_padding * 2;
|
|
return height;
|
|
}
|
|
void Text_Shower::paintEvent(QPaintEvent*) {
|
|
QPainter painter(this);
|
|
painter.setRenderHint(QPainter::Antialiasing);
|
|
QRect r = rect();
|
|
painter.setBrush(QColor(255, 255, 255));
|
|
painter.setPen(QPen(QColor(0, 0, 0), 1));
|
|
painter.drawRoundedRect(r.adjusted(0, 0, -1, -1), m_radius, m_radius);
|
|
int y = m_padding;
|
|
if (!m_title.isEmpty()) {
|
|
QFont title_font = font();
|
|
title_font.setBold(true);
|
|
painter.setFont(title_font);
|
|
QFontMetrics title_fm(title_font);
|
|
painter.drawText(m_padding,
|
|
y + title_fm.ascent(),
|
|
m_title);
|
|
y += title_fm.height() + 6;
|
|
painter.setFont(font());
|
|
}
|
|
QRect text_rect(m_padding, y,
|
|
width() - m_padding * 2,
|
|
height() - y - m_padding);
|
|
painter.drawText(text_rect,
|
|
Qt::AlignLeft | Qt::TextWordWrap,
|
|
m_text);
|
|
}
|
|
}
|