fix: 修复 Toast 组件显示始终置顶且显示时移动窗体崩溃问题

This commit is contained in:
寂静的羽夏 2024-09-28 18:55:34 +08:00
parent 204b34447b
commit b2d03972b8
2 changed files with 16 additions and 12 deletions

View File

@ -19,9 +19,10 @@ static const int PADDING = 10;
Toast::Toast(const QString &strContent, const QPixmap &icon, int nToastInterval,
QWidget *parent)
: QWidget(parent), m_strContent(strContent),
m_nToastInterval(nToastInterval), m_nCurrentWindowOpacity(0),
m_nCurrentStayTime(0), m_nStatus(0), m_icon(icon), _parent(parent) {
: QDialog(parent), m_strContent(strContent),
m_nToastInterval(nToastInterval * TIMER_INTERVAL / 1000),
m_nCurrentWindowOpacity(0), m_nCurrentStayTime(0), m_nStatus(0),
m_icon(icon), _parent(parent) {
Q_ASSERT(parent);
init();
}
@ -32,6 +33,8 @@ void Toast::toast(QWidget *parent, const QPixmap &icon,
static Toast *toast = nullptr;
if (toast) {
toast->hide();
toast->destroy();
toast->deleteLater();
}
@ -40,11 +43,13 @@ void Toast::toast(QWidget *parent, const QPixmap &icon,
connect(toast, &Toast::destroyed, [&] { toast = nullptr; });
auto e0 = new EventFilter(QEvent::Move, parent);
auto e1 = new EventFilter(QEvent::Resize, parent);
auto e0 = new EventFilter(QEvent::Move, toast);
auto e1 = new EventFilter(QEvent::Resize, toast);
auto callback = [&](QObject *, QEvent *) {
toast->setToastPos(toast->lastToastPos());
auto callback = [](QObject *, QEvent *) {
if (toast) {
toast->setToastPos(toast->lastToastPos());
}
};
connect(e0, &EventFilter::eventTriggered, toast, callback);
connect(e1, &EventFilter::eventTriggered, toast, callback);
@ -82,8 +87,7 @@ QSize Toast::calculateTextSize() {
void Toast::init() {
setWindowFlags(Qt::Tool | Qt::FramelessWindowHint |
Qt::WindowStaysOnTopHint | Qt::WindowSystemMenuHint |
Qt::BypassWindowManagerHint);
Qt::WindowSystemMenuHint | Qt::BypassWindowManagerHint);
setAttribute(Qt::WA_TranslucentBackground);
setAttribute(Qt::WA_ShowWithoutActivating);

View File

@ -1,13 +1,13 @@
#ifndef TOAST_H
#define TOAST_H
#include <QDialog>
#include <QFont>
#include <QIcon>
#include <QSize>
#include <QString>
#include <QWidget>
class Toast : public QWidget {
class Toast : public QDialog {
Q_OBJECT
Q_PROPERTY(int fontPointSize READ fontPointSize WRITE setFontPointSize)
@ -22,7 +22,7 @@ public:
static void toast(QWidget *parent, const QPixmap &icon,
const QString &strContent, int fontPointSize = 20,
int nToastInterval = 3000);
int nToastInterval = 1500);
virtual ~Toast();