一、功能与演示
消息框快进慢出,定时一段时间后消失
二、源码
Toast.h
#ifndef TOAST_H
#define TOAST_H
#include <QLabel>
#include <QWidget>
class Toast : public QWidget
{
Q_OBJECT
public:
explicit Toast(QWidget *parent = nullptr);
~Toast();
void setText(const QString &text);
void showAnimation(int timeout = 2000);
public:
static void showTip(const QString &text, QWidget *parent = nullptr);
static void showTip(const QString &text, int timeout, QWidget *parent = nullptr);
protected:
virtual void paintEvent(QPaintEvent *event);
};
Toast.cpp
#include "Toast.h"
#include <QGuiApplication>
#include <QPainter>
#include <QPropertyAnimation>
#include <QScreen>
#include <QTimer>
#include <QVBoxLayout>
Toast::Toast(QWidget *parent)
: QWidget(parent)
{
setWindowFlags(windowFlags() | Qt::FramelessWindowHint | Qt::Tool);
setAttribute(Qt::WA_TranslucentBackground, true);
QVBoxLayout *layout = new QVBoxLayout;
QLabel *label = new QLabel(this);
label->setObjectName("labelText");
label->setStyleSheet("background-color: rgba(255,0,0,0.80);"
"border-radius: 16px;"
"color: #FFFFFF;"
"font-family: microsoft yahei;"
"font-size: 30px;"
"padding-left:25px;"
"padding-right:25px;");
label ->setAlignment(Qt::AlignCenter);
label->setWordWrap(true);
layout->addWidget(label);
setLayout(layout);
}
Toast::~Toast()
{
}
void Toast::setText(const QString &text)
{
QLabel *label = this->findChild<QLabel *>("labelText");
label->setText(text);
}
void Toast::showAnimation(int timeout)
{
/* 快进慢出 */
show();
QTimer::singleShot(timeout, [&]
{
/* 结束动画 */
QPropertyAnimation *animation = new QPropertyAnimation(this, "windowOpacity");
animation->setDuration(1000);
animation->setStartValue(1);
animation->setEndValue(0);
animation->start();
connect(animation, &QPropertyAnimation::finished, [&]
{
close();
deleteLater();
});
});
}
void Toast::showTip(const QString &text, QWidget *parent)
{
Toast *toast = new Toast(parent);
toast->setWindowFlags(toast->windowFlags() | Qt::WindowStaysOnTopHint); /* 置顶 */
toast->setText(text);
toast->adjustSize();
QScreen *pScreen = QGuiApplication::primaryScreen();
toast->move((pScreen->size().width() - toast->width()) / 2, pScreen->size().height() * 0.4);
toast->showAnimation();
}
void Toast::showTip(const QString &text, int timeout, QWidget *parent)
{
Toast *toast = new Toast(parent);
toast->setWindowFlags(toast->windowFlags() | Qt::WindowStaysOnTopHint);
toast->setText(text);
toast->adjustSize();
QScreen *pScreen = QGuiApplication::primaryScreen();
toast->move((pScreen->size().width() - toast->width()) / 2, pScreen->size().height() * 0.4);
toast->showAnimation(timeout);
}
void Toast::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter paint(this);
auto kBackgroundColor = QColor(255, 255, 255);
kBackgroundColor.setAlpha(0.0 * 255);
paint.setPen(Qt::NoPen);
paint.setBrush(QBrush(kBackgroundColor, Qt::SolidPattern));
paint.drawRect(0, 0, width(), height());
}
使用方式
Toast::showTip(tr("Camera disconnected"), 1000, nullptr);