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

相关推荐
郝学胜-神的一滴3 分钟前
使用QVideoWidget实现高效视频播放:从基础到高级应用
开发语言·c++·qt·程序人生·音视频
秋漓4 分钟前
浏览器访问跨域
开发语言·lua
Cher ~4 分钟前
【数据结构】stl 容器
开发语言·数据结构·c++
老蒋每日coding12 分钟前
Go语言实现 Agent Demo
开发语言·后端·golang
czliutz15 分钟前
R语言gm音乐包的使用简单介绍
开发语言·r语言·音乐·技巧
叶之道15 分钟前
MacOS 配置 Qt 开发环境
qt·macos
爱吃泡芙的小白白20 分钟前
Qt 3D老树新花:为何在工业与车载领域仍是首选?
开发语言·qt·3d
余衫马21 分钟前
Qt for Python:PySide6 入门指南
开发语言·c++·python·qt
好像不对劲30 分钟前
python去除pdf白边
开发语言·python·pdf·kindle
C++ 老炮儿的技术栈32 分钟前
#include <filename.h> 和 #include “filename.h” 有什么区别?
linux·c语言·开发语言·c++·windows·visual studio