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

相关推荐
tanyongxi6619 分钟前
C++ 特殊类设计与单例模式解析
java·开发语言·数据结构·c++·算法·单例模式
遗憾皆是温柔21 分钟前
24. 什么是不可变对象,好处是什么
java·开发语言·面试·学习方法
wearegogog12341 分钟前
C语言中的输入输出函数:构建程序交互的基石
c语言·开发语言·交互
Fine姐44 分钟前
The Network Link Layer: 无线传感器中Delay Tolerant Networks – DTNs 延迟容忍网络
开发语言·网络·php·硬件架构
HAPPY酷1 小时前
给纯小白的Python操作 PDF 笔记
开发语言·python·pdf
liulilittle1 小时前
BFS寻路算法解析与实现
开发语言·c++·算法·宽度优先·寻路算法·寻路
阿珊和她的猫2 小时前
autofit.js: 自动调整HTML元素大小的JavaScript库
开发语言·javascript·html
喜欢吃燃面2 小时前
C++算法竞赛:位运算
开发语言·c++·学习·算法
草莓熊Lotso2 小时前
《详解 C++ Date 类的设计与实现:从运算符重载到功能测试》
开发语言·c++·经验分享·笔记·其他