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")就可以了。

相关推荐
.ZGR.1 分钟前
C语言:数组的增删查改2.0
c语言·开发语言
漫漫不慢.4 分钟前
算法练习-二分查找
java·开发语言·算法
掘根30 分钟前
【Qt】绘图
开发语言·qt
咖啡续命又一天1 小时前
python 自动化采集 ChromeDriver 安装
开发语言·python·自动化
ajassi20001 小时前
开源 C++ QT QML 开发(十一)通讯--TCP服务器端
c++·qt·开源
huohaiyu1 小时前
synchronized (Java)
java·开发语言·安全·synchronized
_OP_CHEN1 小时前
C++基础:(九)string类的使用与模拟实现
开发语言·c++·stl·string·string类·c++容器·stl模拟实现
蓝天智能2 小时前
QT MVC中View的特点及使用注意事项
开发语言·qt·mvc
木觞清2 小时前
喜马拉雅音频链接逆向实战
开发语言·前端·javascript
wuxuanok2 小时前
苍穹外卖 —— 公共字段填充
java·开发语言·spring boot·spring·mybatis