Qt QSplashScreen点击即隐藏:如何禁用该默认行为?
禁用QSplashScreen点击隐藏的默认行为
在Qt 6.4.2中,QSplashScreen的点击隐藏是默认内置逻辑,你可以通过以下两种可靠方式禁用该行为:
方法一:子类化QSplashScreen并重写鼠标事件
直接重写鼠标按下与释放事件,不调用父类的默认实现,就能阻断点击触发的关闭逻辑:
#include <QSplashScreen> #include <QMouseEvent> class NoClickSplash : public QSplashScreen { Q_OBJECT public: explicit NoClickSplash(const QPixmap& pixmap, Qt::WindowFlags f = Qt::SplashScreen) : QSplashScreen(pixmap, f) {} protected: void mousePressEvent(QMouseEvent*) override { // 空实现,跳过父类的点击关闭逻辑 } void mouseReleaseEvent(QMouseEvent*) override { // 拦截鼠标释放事件,避免后续触发默认行为 } };
使用时直接实例化该子类:
QPixmap splashPix(":/splash.png"); NoClickSplash splash(splashPix); splash.show(); // 3秒后显示主窗口并关闭启动屏 QTimer::singleShot(3000, [&](){ MainWindow w; w.show(); splash.finish(&w); });
方法二:安装事件过滤器拦截点击相关事件
如果不想子类化,可给QSplashScreen实例安装事件过滤器,拦截所有鼠标点击类事件:
#include <QSplashScreen> #include <QEvent> #include <QMouseEvent> class SplashEventFilter : public QObject { Q_OBJECT protected: bool eventFilter(QObject* obj, QEvent* event) override { auto splash = qobject_cast<QSplashScreen*>(obj); if (splash && (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseButtonRelease)) { return true; // 拦截事件,阻止默认关闭逻辑触发 } return QObject::eventFilter(obj, event); } }; // 使用示例 int main(int argc, char *argv[]) { QApplication app(argc, argv); QPixmap splashPix(":/splash.png"); QSplashScreen splash(splashPix); SplashEventFilter filter; splash.installEventFilter(&filter); splash.show(); QTimer::singleShot(3000, [&](){ MainWindow w; w.show(); splash.finish(&w); }); return app.exec(); }
你之前尝试无效的可能原因
- 子类化时若在重写的鼠标事件中调用了
QSplashScreen::mousePressEvent(event),会触发默认关闭逻辑; - 事件过滤器若只拦截了单一鼠标事件(比如仅拦截按下未拦截释放),可能无法完全阻断触发链;
- 点击触发的
QEvent::WindowStateChange和QEvent::Hide是关闭行为的结果,而非根源,拦截这类事件不如直接阻止鼠标事件有效。
内容的提问来源于stack exchange,提问作者MaPo
相关产品推荐
相关产品推荐

