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

相关推荐
步菲1 小时前
springboot canche 无法避免Null key错误, Null key returned for cache operation
java·开发语言·spring boot
知远同学6 小时前
Anaconda的安装使用(为python管理虚拟环境)
开发语言·python
小徐Chao努力6 小时前
【Langchain4j-Java AI开发】09-Agent智能体工作流
java·开发语言·人工智能
CoderCodingNo6 小时前
【GESP】C++五级真题(贪心和剪枝思想) luogu-B3930 [GESP202312 五级] 烹饪问题
开发语言·c++·剪枝
kylezhao20197 小时前
第1章:第一节 开发环境搭建(工控场景最优配置)
开发语言·c#
啃火龙果的兔子7 小时前
JavaScript 中的 Symbol 特性详解
开发语言·javascript·ecmascript
热爱专研AI的学妹7 小时前
数眼搜索API与博查技术特性深度对比:实时性与数据完整性的核心差异
大数据·开发语言·数据库·人工智能·python
Mr_Chenph7 小时前
Miniconda3在Windows11上和本地Python共生
开发语言·python·miniconda3
阿狸远翔7 小时前
Protobuf 和 protoc-gen-go 详解
开发语言·后端·golang
永远前进不waiting7 小时前
C复习——1
c语言·开发语言