PyQt:消息框在几秒钟后自动关闭

4

我正在尝试创建一个警告消息框,它会在几秒钟后自动消失。

我已经编写了以下代码:

def warning(self):
   messagebox = QtGui.QMessageBox(self)
   messagebox.setWindowTitle("wait")
   messagebox.setText("wait (closing automatically in {0} secondes.)".format(3))
   messagebox.setStandardButtons(messagebox.NoButton)
   self.timer2 = QtCore.QTimer()
   self.time_to_wait = 3
   def close_messagebox(e):
      e.accept()
      self.timer2.stop()
      self.time_to_wait = 3
   def decompte():
      messagebox.setText("wait (closing automatically in {0} secondes.)".format(self.time_to_wait))
      if self.time_to_wait <= 0:
         messagebox.closeEvent = close_messagebox
         messagebox.close()
      self.time_to_wait -= 1
   self.connect(self.timer2,QtCore.SIGNAL("timeout()"),decompte)
   self.timer2.start(1000)
   messagebox.exec_()

实际上,自动关闭部分是正常工作的。

我的问题是,当有人在几秒钟内手动关闭它时,通过单击窗口的x按钮,消息框永远不会关闭。 "等待时间" 变为负数,消息框显示例如 "在-4秒内自动关闭",并且它永远不会关闭。

有什么想法可以避免这种情况吗? 谢谢。


尝试使用我的解决方案。 - eyllanesc
2个回答

8

试试我的解决方案,我创建了一种新类型的QMessageBox,符合您的要求。

import sys
from PyQt4 import QtCore
from PyQt4 import QtGui


class TimerMessageBox(QtGui.QMessageBox):
    def __init__(self, timeout=3, parent=None):
        super(TimerMessageBox, self).__init__(parent)
        self.setWindowTitle("wait")
        self.time_to_wait = timeout
        self.setText("wait (closing automatically in {0} secondes.)".format(timeout))
        self.setStandardButtons(QtGui.QMessageBox.NoButton)
        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.changeContent)
        self.timer.start()

    def changeContent(self):
        self.setText("wait (closing automatically in {0} secondes.)".format(self.time_to_wait))
        self.time_to_wait -= 1
        if self.time_to_wait <= 0:
            self.close()

    def closeEvent(self, event):
        self.timer.stop()
        event.accept()


class Example(QtGui.QWidget):
    def __init__(self):
        super(Example, self).__init__()
        btn = QtGui.QPushButton('Button', self)
        btn.resize(btn.sizeHint())
        btn.move(50, 50)
        self.setWindowTitle('Example')
        btn.clicked.connect(self.warning)

    def warning(self):
        messagebox = TimerMessageBox(5, self)
        messagebox.exec_()


def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

1
你的计数器存在一个偏移错误。你应该将 self.time_to_wait -= 1 移动到 changeContent 的末尾。然后在启动计时器之前,删除 __init__ 中的 setText 调用,并调用 self.changeContent()。 (PS:如果你使用 新式信号和槽语法,会更好一些)。 - ekhumoro
@ekhumoro 更新答案 - eyllanesc
@ekhumoro 请检查我的解决方案。 - eyllanesc
我已经检查过了,它有我在上一条评论中描述的错误。我也在第一条评论中展示了如何修复它。 - ekhumoro
谢谢!(抱歉回复晚了...)它完美地工作了。再次感谢!! - p.deman
显示剩余3条评论

4

使用PyQt5

from PyQt5.QtCore import QTimer
time_milliseconds = 1000

QTimer.singleShot(time_milliseconds, lambda : messageBox.done(0))

1
真的是一个非常简单和不错的解决方案。 - cubaguest

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接