• Qt 消息小弹窗


    背景:

    Qt程序中,经常要使用弹窗来显示一些报警或提示信息,需要人机互动的直接选择模态弹窗就可以,但是有些只是提醒,并不需要阻塞程序运行的消息提醒,使用小弹窗再合适不过了,类似效果就是手机顶部的气泡弹窗。       


    思路:

    Qt官方并没有提供这么一个类,一些开源组件中是有的,但是可能存在一些不兼容的情况,比如消息的设定方面,或者使用时会遇到一些莫名其妙的bug,那就自己写一个简单的,日后需要美化或复杂功能时再完善。


    实现:

    不使用designer,直接代码即可。

    .h

    1. #include
    2. class CustomSnakeBar : public QWidget {
    3. Q_OBJECT
    4. public:
    5. explicit CustomSnakeBar( QWidget *parent = nullptr );
    6. void showMessage( const QString &message, int duration = 3000 );
    7. private slots:
    8. void hide();
    9. private:
    10. QTimer *timer;
    11. };

    解决方案:

    .cpp

    1. #include "customsnakebar.h"
    2. #include <QHBoxLayout>
    3. #include <QLabel>
    4. #include <QTimer>
    5. CustomSnakeBar::CustomSnakeBar( QWidget *parent )
    6. : QWidget( parent ) {
    7. setWindowFlags( Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint );
    8. setAttribute( Qt::WA_TranslucentBackground );
    9. setStyleSheet( " background-color: #FFA54F;font:22px;"
    10. "border-radius:5px;" );
    11. QHBoxLayout *layout = new QHBoxLayout( this );
    12. QLabel * messageLabel = new QLabel( this );
    13. layout->addWidget( messageLabel );
    14. timer = new QTimer( this );
    15. connect( timer, &QTimer::timeout, this, &CustomSnakeBar::hide );
    16. }
    17. void CustomSnakeBar::showMessage( const QString &message, int duration ) {
    18. QLabel *messageLabel = findChild<QLabel *>();
    19. messageLabel->setText( message );
    20. adjustSize();
    21. move( parentWidget()->x() + parentWidget()->width() / 2 - width() / 2, 0 );
    22. show();
    23. timer->start( duration );
    24. }
    25. void CustomSnakeBar::hide() {
    26. timer->stop();
    27. close();
    28. }

    使用的话,在需要的地方直接showMessage(“XXX”)就可以了。

  • 相关阅读:
    duda+显卡驱动+pytorch版本对应
    C++—— pass by value and use std::move
    webfunny埋点漏斗功能
    flink之Sink to MySQL和Redis
    c++小学生入门课程(一)
    LiDAR 完整指南介绍:激光探测和测距
    前端笔试题总结,带答案和解析
    ​怎么测试websocket接口
    New的原理
    Android开发之打卡功能
  • 原文地址:https://blog.csdn.net/baidu_33879812/article/details/132965913