qt实现带数字的消息通知

cpp 复制代码
#include <QPushButton>
#include <QLabel>
#include <QHBoxLayout>

class BadgeButton : public QPushButton
{
    Q_OBJECT
public:
    explicit BadgeButton(QWidget *parent = nullptr) : QPushButton(parent)
    {
        // 创建提示徽章(红色背景+数字)
        m_badge = new QLabel(this);
        m_badge->setStyleSheet(R"(
            background-color: red;
            color: white;
            border-radius: 8px;  /* 圆角 */
            font-size: 12px;
            padding: 0px 4px;    /* 左右留白,让数字居中 */
        )");
        m_badge->setAlignment(Qt::AlignCenter);  // 文字居中
        m_badge->hide();  // 默认隐藏
    }

    // 设置未读数量(0则隐藏,>9显示"9+")
    void setUnreadCount(int count)
    {
        if (count <= 0) {
            m_badge->hide();
            return;
        }
        // 超过9条显示"9+"
        m_badge->setText(count > 9 ? "9+" : QString::number(count));
        // 调整徽章大小(根据文字长度自动适应)
        m_badge->adjustSize();
        // 确保最小尺寸(至少能显示一个数字)
        m_badge->setMinimumSize(16, 16);
        m_badge->show();
        // 更新位置
        updateBadgePosition();
    }

protected:
    // 按钮大小改变时更新徽章位置
    void resizeEvent(QResizeEvent *event) override
    {
        QPushButton::resizeEvent(event);
        updateBadgePosition();
    }

private:
    QLabel *m_badge;

    // 更新徽章到右上角
    void updateBadgePosition()
    {
        if (!m_badge->isVisible()) return;
        // 右上角定位(向右上方偏移,避免完全贴边)
        int x = width() - m_badge->width() + 2;  // 右偏移2px(部分超出按钮边缘更美观)
        int y = -m_badge->height() / 2;          // 上偏移一半高度(部分超出顶部)
        m_badge->move(x, y);
    }
};

使用方法

cpp 复制代码
BadgeButton *btn = new BadgeButton(this);
btn->setText("消息");
btn->setGeometry(50, 50, 100, 40);
btn->setUnreadCount(3);  // 显示3条未读
// btn->setUnreadCount(15);  // 显示"9+"
相关推荐
程序leo源13 小时前
Qt窗口详解
开发语言·数据库·c++·qt·青少年编程·c#
我在人间贩卖青春14 小时前
重学Qt——事件处理
qt
小宋00114 小时前
QT中控件qss样式修改
开发语言·qt
yuechuji00118 小时前
三、MPR(三平面重建)和三视图
qt
Hua-Jay19 小时前
OpenCV联合C++/Qt 学习笔记(二十二)----相机模型与投影及单目相机标定
c++·笔记·qt·opencv·学习·计算机视觉
小短腿的代码世界21 小时前
QCefView架构深度解析:从Chromium嵌入到Qt信号槽集成的完整技术链路
qt·架构
byxdaz1 天前
Qt修改操作系统的日期与时间
qt
小短腿的代码世界1 天前
Qt属性系统揭秘:从Q_PROPERTY宏到动态元对象系统的完整架构解析
开发语言·qt·架构
丁劲犇1 天前
QodeAssist:为msys2 ucrt64 Qt Creator 注入 AI 灵魂的开源插件
开发语言·人工智能·qt
listhi5201 天前
基于QT的串口心电波形实时显示系统
开发语言·qt