首页 > 解决方案 > 有没有办法检查 PyQt5 窗口是否打开并相应地延迟另一个实例?

问题描述

我是 Python3 和 PyQt5 的新手。我制作了一个 PyQt5 模板来显示通知。所以最后我有一个函数 [notification()] 在屏幕上显示通知。

但问题是,当我同时多次调用 notification() 时,只有第一个显示,然后程序退出。(最后有一个测试用例 - 注意只有第一个弹出

有没有办法让我能够暂停第二个通知,直到第一个通知完成,然后调用该函数(可能使用标志或其他东西)。

import sys
from PyQt5.QtWidgets import QVBoxLayout,QLabel,QDesktopWidget,QWidget,QApplication
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt,QTimer

class SpecialBG(QLabel):
    def __init__(self, parent):
        QLabel.__init__(self, parent)
        self.setStyleSheet(
                "color: rgba(237,174,28,100%);"
                "background-color: rgba(247,247,247,95%);"
                "text-align: center;"
                "border-radius: 20px;"
                "padding: 0px;"
                )

class SimpleRoundedCorners(QWidget):
    def __init__(self,title,minutes):
        self.title = title 
        self.minutes = minutes

        super(SimpleRoundedCorners, self).__init__()
        self.initUI()
        QTimer.singleShot(5500, self.exeunt)

    def exeunt(self):
        self.close
        exit()

    def initUI(self):
        winwidth = 650
        winheight = 150

        font = QFont()
        font.setFamily("SF Pro Display")
        font.setPointSize(20)

        font2 = QFont()
        font2.setFamily("SF Pro Display")
        font2.setPointSize(18)

        VBox = QVBoxLayout()
        roundyround = SpecialBG(self)
        VBox.addWidget(roundyround)

        VBox.pyqtConfigure
        self.setLayout(VBox)
        self.setWindowFlags(
                  Qt.FramelessWindowHint
                | Qt.WindowStaysOnTopHint
                | Qt.SplashScreen
                )

        self.setAttribute(Qt.WA_TranslucentBackground, True)

        taskTitle = QLabel(self)
        taskTitle.move(120, 40)
        taskTitle.setFont(font)
        taskTitle.setText(self.title)
        taskTitle.adjustSize()

        timeLeft = QLabel(self)
        timeLeft.move(120, 80)
        timeLeft.setFont(font2)
        timeLeft.setText("in "+str(self.minutes)+" minutes")
        timeLeft.adjustSize()

        self.setGeometry(1260, 5, winwidth, winheight)
        self.setWindowTitle('Simple Rounded Corners')
        self.show()

# this is the function
def notification(title,minutes):
    app = QApplication(sys.argv)
    alldone = SimpleRoundedCorners(title,minutes)
    sys.exit(app.exec_())

# test-cases
notification("notification #1",5)
notification("notification #2",10)

标签: pythonpython-3.xpyqtpyqt5

解决方案


问题是您使用exit()的是未定义的,您应该使用sys.exit(),但这仍然是一个错误,因为使用该功能将关闭完整的应用程序,因为这是它的功能,而您只需要关闭 QApplication:

# ...
class SimpleRoundedCorners(QWidget):
    # ...
    def exeunt(self):
        QApplication.quit()
    # ...
# this is the function
def notification(title, minutes):
    app = QApplication(sys.argv)
    alldone = SimpleRoundedCorners(title, minutes)
    app.exec_()

推荐阅读