具有倒数计时器的

时间:2016-05-13 13:03:24

标签: python user-interface pyqt4

我在实验室中编写了一个python应用程序,用于通过不稳定的网络连接将数据保存到远程数据库中。当连接断开时,会弹出一个问题(我使用QMessageBox.question),询问用户是重复上一次交易还是取消它。

最近修改了应用程序以在夜间自动进行自动测量。没有操作员可以点击默认选项"重试"!它应该在一些超时后自动选择,仍然让用户有机会做出其他选择。

enter image description here

这意味着,如果用户没有做出任何其他选择,我需要一个QMessageBox版本,在超时后点击默认按钮。

similar question,但具体为C++

1 个答案:

答案 0 :(得分:3)

此答案是对Jeremy Friesner in a similar question发布的Python代码的C++改编:

from PyQt4.QtGui import QMessageBox as MBox, QApplication
from PyQt4.QtCore import QTimer


class TimedMBox(MBox):
    """
    Variant of QMessageBox that automatically clicks the default button
    after the timeout is elapsed
    """
    def __init__(self, timeout=5, buttons=None, **kwargs):
        if not buttons:
            buttons = [MBox.Retry, MBox.Abort, MBox.Cancel]

        self.timer = QTimer()
        self.timeout = timeout
        self.timer.timeout.connect(self.tick)
        self.timer.setInterval(1000)
        super(TimedMBox, self).__init__(parent=None)

        if "text" in kwargs:
            self.setText(kwargs["text"])
        if "title" in kwargs:
            self.setWindowTitle(kwargs["title"])
        self.t_btn = self.addButton(buttons.pop(0))
        self.t_btn_text = self.t_btn.text()
        self.setDefaultButton(self.t_btn)
        for button in buttons:
            self.addButton(button)

    def showEvent(self, e):
        super(TimedMBox, self).showEvent(e)
        self.tick()
        self.timer.start()

    def tick(self):
        self.timeout -= 1
        if self.timeout >= 0:
            self.t_btn.setText(self.t_btn_text + " (%i)" % self.timeout)
        else:
            self.timer.stop()
            self.defaultButton().animateClick()

    @staticmethod
    def question(**kwargs):
        """
        Ask user a question, which has a default answer. The default answer is
        automatically selected after a timeout.

        Parameters
        ----------

        title : string
            Title of the question window

        text : string
            Textual message to the user

        timeout : float
            Number of seconds before the default button is pressed

        buttons : {MBox.DefaultButton, array}
            Array of buttons for the dialog, default button first

        Returns
        -------
        button : MBox.DefaultButton
            The button that has been pressed
        """
        w = TimedMBox(**kwargs)
        w.setIcon(MBox.Question)
        return w.exec_()



if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    w = TimedMBox.question(text="Please select something",
                           title="Timed Message Box",
                           timeout=8)
    if w == MBox.Retry:
        print "Retry"
    if w == MBox.Cancel:
        print "Cancel"
    if w == MBox.Abort:
        print "Abort"

在此实现中,默认按钮是参数buttons中的第一个按钮。