QT 定时自动关闭消息提示框简单实现

                                              QT 定时自动关闭消息提示框简单实现 

一、简述

        记--使用Qt简单实现提示框简单,可定时自动关闭。

        例子打包:外链:https://wwm.lanzouv.com/b0cau3tid 密码:g3ob

二、效果

 

三、工程结构

 

UI界面

四、源文件 

NoticeWidget.pro文件

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = Notice
TEMPLATE = app


SOURCES += main.cpp\
        mainwindow.cpp \
    noticewidget.cpp

HEADERS  += mainwindow.h \
    noticewidget.h

FORMS    += mainwindow.ui

mainwindow.h文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "noticewidget.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_pushButtonShowNotice_clicked();

private:
    Ui::MainWindow *ui;
    NoticeWidget noticeWin;
};

#endif // MAINWINDOW_H

mainwindow.cpp文件

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("定时自动关闭消息提示框");
    ui->plainTextEditMsg->setPlainText("定时自动关闭消息提示框测试,简单测试例子");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButtonShowNotice_clicked()
{    
    noticeWin.Notice(this, ui->plainTextEditMsg->toPlainText(), 20000);
}

noticewidget.h文件

#ifndef _NoticeWidget_H_
#define _NoticeWidget_H_

#include <QLabel>
#include <QTimer>
#include <QList>

//定时器间隔,单位ms
#define TIMER_INTERVAL_MS   50

//默认提示时间1s
#define NOTICE_DEF_DELAY_CNT     (1000/TIMER_INTERVAL_MS)

//透明度最大值255,也就是不透明
#define TRANSPARENT_MAX_VAL 255

//透明度递减值
#define TRANSPARENT_CUT_VAL (TRANSPARENT_MAX_VAL/NOTICE_DEF_DELAY_CNT + 1)

//大小比例
#define SIZE_SCALE  0.8

//高度补偿
#define PATCH_HEIGHT    10

//样式,字体颜色:白色;圆角;背景色透明度
#define STYLE_SHEET "color:white;border-radius:8px;background-color:rgba(80, 80, 80, %1);"

class NoticeWidget :public QLabel
{
    Q_OBJECT

public:
    void Notice(QWidget *parent, const QString &msg, const int delay_ms = 2000);

public:
    explicit NoticeWidget(QWidget *parent = 0);
    ~NoticeWidget();

private:
    void SetMesseage(const QString &msg, int delay_ms);
    void ChangeSize();

public slots:
    void OnTimerTimeout();

private:
    QWidget *mParentPtr;
    QTimer  *mTimerPtr;
    int mTimerCount;
    int mBaseWidth;  //按一行时算的宽度
    int mBaseHeight; //一行高度
    int mMinHeight; //最小高度
    int mTransparentVal;//透明度0~255,值越小越透明
    QList<int> mListLinesLen;
};

#endif // _NoticeWidget_H_

noticewidget.cpp文件

#include "noticewidget.h"

NoticeWidget::NoticeWidget(QWidget *parent)
    : mParentPtr(parent)
    , mTimerPtr(nullptr)
    , mTimerCount(NOTICE_DEF_DELAY_CNT)
    , mBaseWidth(0)
    , mBaseHeight(0)
    , mMinHeight(0)
    , mTransparentVal(TRANSPARENT_MAX_VAL)

{
    //文字居中
    setAlignment(Qt::AlignCenter);

    //定时器,定时消失
    mTimerPtr = new QTimer();
    connect(mTimerPtr, SIGNAL(timeout()), this, SLOT(OnTimerTimeout()), Qt::UniqueConnection);
}

NoticeWidget::~NoticeWidget()
{
    if (mTimerPtr->isActive()) {
        mTimerPtr->stop();
    }
    delete mTimerPtr;
    deleteLater();
}

void NoticeWidget::OnTimerTimeout()
{
    --mTimerCount;
    if (0 < mTimerCount) {
        //重新定位(窗口大小和位置可能变化)
        if (nullptr != mParentPtr) {
            QPoint pt((mParentPtr->width() - width()) >> 1, (mParentPtr->height() - height()) >> 1);
            if (pos() != pt) {//父窗口位置变化
                ChangeSize();
                move(pt);
            }
        }
        //最后1s开始渐变消失
        if (mTimerCount <= NOTICE_DEF_DELAY_CNT && 0 < mTransparentVal) {
            mTransparentVal -= TRANSPARENT_CUT_VAL;
            if (0 > mTransparentVal) {
                mTransparentVal = 0;
            }
            //控制透明度
            setStyleSheet(QString(STYLE_SHEET).arg(mTransparentVal));
        }
    } else {//显示结束
        mTimerPtr->stop();
        setVisible(false);        
    }
}

//设置要显示的消息
void NoticeWidget::SetMesseage(const QString &msg, int delay_ms)
{
    QStringList strList = msg.split("\n");
    QFontMetrics fontMetrics(font());
    mListLinesLen.clear();

    int tmpW = 0;
    int maxLineLen = 1; //最长那一行的长度
    foreach (QString s, strList) {
        tmpW = fontMetrics.width(s);
        mListLinesLen.append(tmpW);
        if (maxLineLen < tmpW) {
            maxLineLen = tmpW;
        }
    }

    mParentPtr = parentWidget();
    mBaseWidth = fontMetrics.width(msg);
    mBaseHeight = fontMetrics.lineSpacing() + PATCH_HEIGHT;
    mMinHeight = (mBaseWidth * mBaseHeight)/maxLineLen + 1;//面积除以最长的宽就是最小的高

    //设置宽高
    ChangeSize();

    //换行
    setWordWrap(true);

    //设置显示内容
    setText(msg);

    //居中
    if (nullptr != mParentPtr) {
        move((mParentPtr->width() - width()) >> 1, (mParentPtr->height() - height()) >> 1);
    }

    setVisible(true);//显示
    setStyleSheet(QString(STYLE_SHEET).arg(TRANSPARENT_MAX_VAL));//设置样式,不透明
    mTimerCount = delay_ms/TIMER_INTERVAL_MS + 1;//延时计数计算
    mTransparentVal = TRANSPARENT_MAX_VAL;
}

//跟随父窗口大小变化
void NoticeWidget::ChangeSize()
{
    if (nullptr != mParentPtr) {
        double wd = mParentPtr->width() * SIZE_SCALE;//宽度占父窗口的80%
        //提示内容多少决定提示框面积,长方形面积s=mBaseHeight*mBaseWidth
        //面积s固定,当mBaseWidth跟随窗体宽度变大而增大,那么mBaseHeight应当变小,才维持s固定
        int newH = (mBaseHeight*mBaseWidth)/wd + PATCH_HEIGHT;
        if (newH < (mMinHeight + mBaseHeight)) {//设定最小高度
            newH = mMinHeight + mBaseHeight;
        } else {
            foreach (int lineLen, mListLinesLen) {
                if (lineLen > wd) {//某一行长度大于当前宽度就会发生折行,高度需要增加
                    newH += mBaseHeight;
                }
            }
        }

        setFixedSize((int)wd, newH);
    }
}

//显示消息,可通过设置delay_ms=0来立即关闭显示
void NoticeWidget::Notice(QWidget *parent, const QString &msg, const int delay_ms)
{
    if (mTimerPtr->isActive()) {
        mTimerPtr->stop();
        setVisible(false);
    }

    //消息为空直接返回
    if (msg.isEmpty() || 0 >= delay_ms) {
        return;
    }

    setParent(parent);
    SetMesseage(msg, delay_ms);
    mTimerPtr->start(TIMER_INTERVAL_MS);//开始计数
}

main.cpp文件

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值