You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt5实现模态弹窗:阻止外部窗口点击并锁定后台交互

问题:实现模态定时弹窗(拦截后台交互)

我需要实现一个弹窗式窗口,每2分钟弹出一次(定时逻辑后续自行实现)。要求点击按钮关闭窗口前,无法与后台应用进行交互。我尝试了两段代码但均未成功,第一段代码中的全屏与透明设置是为了实现鼠标捕获效果,因此第二段代码未添加这些设置。

第一段尝试代码

from PyQt5.QtWidgets import QApplication,QMainWindow,QPushButton,QLabel,QWidget,QVBoxLayout
from PyQt5.QtCore import Qt
from sys import argv, exit

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.iniui()
        self.showFullScreen()

    def iniui(self):
        main_widget = QWidget()
        main_lay = QVBoxLayout()
        main_lay.setAlignment(Qt.AlignCenter)

        a = QLabel("A")
        a.setFixedSize(200,200)
        a.setStyleSheet("background-color:red")
        main_lay.addWidget(a)

        main_lay.setContentsMargins(0, 0, 0, 0)

        main_widget.setLayout(main_lay)
        main_widget.setAttribute(Qt.WA_TranslucentBackground)

        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setCentralWidget(main_widget)


    def mousePressEvent(self, event):
        print(event.pos())
        event.ignore()

if __name__ == "__main__":
    app = QApplication(argv)
    window = Window()
    exit(app.exec_())

第二段尝试代码

from PySide2.QtWidgets import QApplication, QMainWindow, QWidget, QLabel, QVBoxLayout

from sys import argv, exit

class Win(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui()
        self.show()

    def ui(self):
        main_widget = QWidget()
        main_layout = QVBoxLayout()
        label = QLabel("A")
        main_layout.addWidget(label)
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)
        self.grabMouse()

if __name__ == '__main__':
    app = QApplication(argv)
    window = Win()
    exit(app.exec_())

内容的提问来源于stack exchange,提问作者makalidap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 19:43:26