最近做用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,感兴趣的朋友点个关注
转载请注明出处