
cpp
#ifndef BTNQLABELDEMO_H
#define BTNQLABELDEMO_H
#include <QWidget>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
// 自定义带消息提示的按钮
class BadgeButton : public QPushButton
{
Q_OBJECT
public:
explicit BadgeButton(QWidget *parent = nullptr) : QPushButton(parent)
{
// 创建红色提示原点
m_badge = new QLabel(this);
m_badge->setFixedSize(10, 10); // 原点大小
m_badge->setStyleSheet("background-color: red; border-radius: 5px;"); // 圆形样式
m_badge->hide(); // 默认隐藏
// 设置原点位置(右上角)
updateBadgePosition();
}
// 显示/隐藏提示原点
void setBadgeVisible(bool visible)
{
m_badge->setVisible(visible);
}
protected:
// 按钮大小改变时更新原点位置
void resizeEvent(QResizeEvent *event) override
{
QPushButton::resizeEvent(event);
updateBadgePosition();
}
private:
QLabel *m_badge;
// 更新原点位置到右上角
void updateBadgePosition()
{
int x = width() - m_badge->width() - 2; // 靠右偏移2px
int y = 2; // 靠上偏移2px
m_badge->move(x, y);
}
};
#endif // BTNQLABELDEMO_H