Qt 消息小弹窗

背景:

Qt程序中,经常要使用弹窗来显示一些报警或提示信息,需要人机互动的直接选择模态弹窗就可以,但是有些只是提醒,并不需要阻塞程序运行的消息提醒,使用小弹窗再合适不过了,类似效果就是手机顶部的气泡弹窗。


思路:

Qt官方并没有提供这么一个类,一些开源组件中是有的,但是可能存在一些不兼容的情况,比如消息的设定方面,或者使用时会遇到一些莫名其妙的bug,那就自己写一个简单的,日后需要美化或复杂功能时再完善。


实现:

不使用designer,直接代码即可。

.h

复制代码
#include <QWidget>

class CustomSnakeBar : public QWidget {
    Q_OBJECT

  public:
    explicit CustomSnakeBar( QWidget *parent = nullptr );
    void showMessage( const QString &message, int duration = 3000 );

  private slots:
    void hide();

  private:
    QTimer *timer;
};

解决方案:

.cpp

复制代码
#include "customsnakebar.h"
#include <QHBoxLayout>
#include <QLabel>
#include <QTimer>

CustomSnakeBar::CustomSnakeBar( QWidget *parent )
    : QWidget( parent ) {
    setWindowFlags( Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint );
    setAttribute( Qt::WA_TranslucentBackground );
    setStyleSheet( " background-color: #FFA54F;font:22px;"
                   "border-radius:5px;" );
    QHBoxLayout *layout       = new QHBoxLayout( this );
    QLabel *     messageLabel = new QLabel( this );
    layout->addWidget( messageLabel );
    timer = new QTimer( this );
    connect( timer, &QTimer::timeout, this, &CustomSnakeBar::hide );
}

void CustomSnakeBar::showMessage( const QString &message, int duration ) {
    QLabel *messageLabel = findChild<QLabel *>();
    messageLabel->setText( message );
    adjustSize();
    move( parentWidget()->x() + parentWidget()->width() / 2 - width() / 2, 0 );
    show();
    timer->start( duration );
}


void CustomSnakeBar::hide() {
    timer->stop();
    close();
}

使用的话,在需要的地方直接showMessage("XXX")就可以了。

相关推荐
艾莉丝努力练剑36 分钟前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
还债大湿兄2 小时前
《C++内存泄漏8大战场:Qt/MFC实战详解 + 面试高频陷阱破解》
c++·qt·mfc
倔强青铜35 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
u_topian5 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
珊瑚里的鱼6 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上6 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
xingshanchang6 小时前
Matlab的命令行窗口内容的记录-利用diary记录日志/保存命令窗口输出
开发语言·matlab
Risehuxyc6 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
AI视觉网奇6 小时前
git 访问 github
运维·开发语言·docker
不知道叫什么呀6 小时前
【C】vector和array的区别
java·c语言·开发语言·aigc