Qt5 封装toast提示框

本文介绍如何使用Qt创建一个Mytoast类,封装用户操作提示功能,如密码错误,提供简单的弹窗效果和定时关闭选项。通过实例展示了如何在项目中应用这个定制化的UI组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近做用Qt做项目,需要对用户的操作进行反馈,如密码错误之类,于是自己封装了一个Mytoast类来实现

先展示效果图:

 

mytoast.h

#ifndef MYTOAST_H
#define MYTOAST_H

#include <QLabel>
#include <QTimer>

//继承QLabel类,父级窗体为QWidget类及派生类
class Mytoast:public QLabel
{
    Q_OBJECT
public:
    Mytoast(QWidget*parent);
    void start(QString str ,int time =-1);
    void stop();

private:
    QTimer *timer = new QTimer;

private slots:
    void time_toast();
};

#endif // MYTOAST_H

mytoast.cpp

#include "mytoast.h"

Mytoast::Mytoast(QWidget*parent):QLabel(parent)
{
    //设置样式
    this->setStyleSheet("background-color: rgba(40, 40, 40, 140);color: rgb(255, 255, 255);border-radius:4px");
    //居中对齐
    this->setAlignment(Qt::AlignCenter);
    //隐藏
    this->hide();
    //信号和槽
    connect(this->timer,&QTimer::timeout,this,&Mytoast::time_toast);
}

//第一个参数为弹窗内容
//第二个参数为持续时间ms,默认-1不消失,需调用stop关闭或重新start
void Mytoast::start(QString str, int time)
{
    //关闭上次弹窗的定时器
    if(timer->isActive())timer->stop();
    //计算字体的宽度和高度,字体可以自己更换
    QFontMetrics metrics(QFont("微软雅黑",10));
    int text_width = metrics.width(str);
    int text_height = metrics.height();
    //设置弹窗大小,增加一些像素更美观一点
    this->resize(text_width+16,text_height+12);
    //设置弹窗内容
    this->setText(str);
    //设置弹窗字体,注意一定要和上面的相同
    this->setFont(QFont("微软雅黑",10));
    //设置位置居中父级窗体
    int p_x = int((this->parentWidget()->width()-this->width())/2);
    int p_y = int((this->parentWidget()->height()-this->height())/2);
    this->move(p_x,p_y);

    //time为-1时不关闭
    if(time == -1){
        this->show();
    }
    //启动定时器
    else{
        this->show();
        this->timer->start(time);
    }

}

//主动调用关闭弹窗,用于time=-1的情况
void Mytoast::stop()
{
    this->timer->stop();
    this->hide();
}

//定时关闭函数
void Mytoast::time_toast()
{
    this->timer->stop();
    this->hide();
}

测试代码 main.cpp

#include "mytoast.h"
#include <QApplication>
#include <QWidget>

int main(int argc, char *argv[])
{
   QApplication app(argc,argv);
   QWidget *w = new QWidget;
   //设置窗体大小
   w->resize(300,200);
   
   //设置toast的父级为w窗体
   Mytoast toast(w);
   toast.start("登录成功",-1);
   //显示w窗体
   w->show();

   return app.exec();
}

后续将发布更多项目demo,感兴趣的朋友点个关注

转载请注明出处

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

开发大观园

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值