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

相关推荐
风与沙的较量丶39 分钟前
Java中的局部变量和成员变量在内存中的位置
java·开发语言
水煮庄周鱼鱼1 小时前
C# 入门简介
开发语言·c#
编程星空1 小时前
css主题色修改后会多出一个css吗?css怎么定义变量?
开发语言·后端·rust
软件黑马王子1 小时前
Unity游戏制作中的C#基础(6)方法和类的知识点深度剖析
开发语言·游戏·unity·c#
Logintern092 小时前
使用VS Code进行Python编程的一些快捷方式
开发语言·python
Multiple-ji2 小时前
想学python进来看看把
开发语言·python
一个小白12 小时前
C++——list模拟实现
开发语言·c++
bug总结2 小时前
新学一个JavaScript 的 classList API
开发语言·javascript·ecmascript
Nicole Potter2 小时前
请说明C#中的List是如何扩容的?
开发语言·面试·c#
程序员老舅2 小时前
C++ Qt项目教程:WebServer网络测试工具
c++·qt·测试工具·webserver·qt项目·qt项目实战