实现思路很简单,就是继承QFrame类,然后在界面里面放置两个QLabel对象。一个lab用于显示背景图,一个用于显示提示的文字。
背景图百度一张图片,然后扣掉背景,如下图所示:
显示文字的QLabel需要矫正位置在框内,然后显示内容居中、自动换行等等设置。
因为没有手动关闭功能,所以还需要定时自动关闭,其实该实现与我之前写的一篇轻弹窗文章是一样的实现。
轻弹窗:https://blog.csdn.net/weixin_42887343/article/details/109303972
头文件
#ifndef LIGHTMESSAGE_H
#define LIGHTMESSAGE_H
#include
class LightMessage : public QFrame
{
Q_OBJECT
public:
static void information(QWidget *parent,
QString info,
int time = 3000,
QString strFontSize = "20px",
QString strColor = "#000000");
signals:
private:
explicit LightMessage(QWidget *parent = nullptr,
QString info = "",
QString strFontSize = "20px",
QString strColor = "#000000");
};
#endif // LIGHTMESSAGE_H
cpp文件
#include "lightMessage.h"
#include
#include
#include
#include
LightMessage::LightMessage(QWidget *parent,QString info, QString strFontSize, QString strColor) : QFrame(parent)
{
//窗口设置
//int width = 200;
//int height = 134;
this->setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);
this->setAttribute(Qt::WA_TranslucentBackground); //设置窗体背景透明
this->resize(200,134);
//刷背景图片
QLabel *pLabelImg = new QLabel(this);
pLabelImg->resize(width(),height());
pLabelImg->setGeometry(0,0,width(),height());
QImage img(":/new/prefix1/resource/lightMessage.png");
QImage img2 = img.scaled(width(),height(),Qt::KeepAspectRatio);
pLabelImg->setPixmap(QPixmap::fromImage(img2));
//刷文字
QLabel *pLabelStr = new QLabel(this);
pLabelStr->setAlignment(Qt::AlignCenter);
pLabelStr->setStyleSheet(QString("QLabel{color:%1;font:%2 SimHei;border-radius:5px;}")
.arg(strColor).arg(strFontSize));
pLabelStr->setText(info);
pLabelStr->adjustSize();
pLabelStr->setGeometry(width()/25,height()/13.5,width()/1.45,height()/2.4);
}
void LightMessage::information(QWidget *parent,QString info, int time, QString strFontSize, QString strColor)
{
LightMessage *widgetPtr = new LightMessage(parent,info,strFontSize,strColor);
if(parent)
{
int x = parent->pos().x();
int y = parent->pos().y() - widgetPtr->height();
widgetPtr->move(x,y-2);
}
if(time < 1100) time = 1100;
QTimer::singleShot(time-1000,widgetPtr,[=]()
{
QPropertyAnimation *pAnimation = new QPropertyAnimation(widgetPtr,"windowOpacity",widgetPtr);
pAnimation->setDuration(1000);
pAnimation->setEasingCurve(QEasingCurve::InCirc);
pAnimation->setStartValue(1.0);
pAnimation->setEndValue(0.0);
pAnimation->start();
connect(pAnimation,&QPropertyAnimation::finished,[=]{
delete widgetPtr;
});
});
widgetPtr->show();
}
其中注意 :/new/prefix1/resource/lightMessage.png 为前面扣的图,然后加入项目资源的图片路径。
使用方法就很简单了,如下:
LightMessage::information(nullptr,"呵...拜拜了您!",2000,"16px");
LightMessage::information(this,"...我再跳!!!");