2016-05-13 40 views
0

我在實驗室編寫了一個用於測量的python應用程序,該應用程序通過不穩定的網絡連接將數據保存到遠程數據庫中。當連接斷開時,彈出一個問題(我使用QMessageBox.question),要求用戶重複上次事務還是取消它。帶有倒數計時器的PyQt4 QMessageBox

最近的應用程序被修改爲在夜間自動進行自動測量。沒有操作員再點擊默認選項「重試」!它應該在一些超時後自動選擇,仍然給用戶做出其他選擇的機會。

enter image description here

這意味着,我需要一個版本QMessageBox提示的是點擊一個默認按鈕的超時時間過去之後,如果用戶沒有做任何其他的選擇。

similar question,但它是C++特定。

回答

3

這個答案是Python適應C++代碼張貼Jeremy Friesner in a similar question

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第一個。