2016-12-02 440 views
1

我試圖做一個警告消息框,幾秒鐘後自動消失。 我已經做了這樣的代碼:pyqt:幾秒後自動關閉messagebox

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秒內自動關閉」,並且它永遠不會關閉。

任何想法,我可以避免這種情況? 問候

+0

嘗試用我的解決方案 – eyllanesc

回答

1

嘗試用我的解決方案, 我創建了一個新的類型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() 
+0

沒有在你的櫃檯關閉的情況一個錯誤。您應該將'self.time_to_wait - = 1'移動到'changeContent'的末尾。然後在啓動定時器之前,在__init__中移除'setText'調用並調用'self.changeContent()'。 (PS:如果你使用[新型信號和插槽語法](http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html)),它也會更好。 – ekhumoro

+0

@ekhumoro這是pyqt4,新式信號和插槽語法僅適用於pyqt5 – eyllanesc

+0

不,它們也在PyQt4中。我給出的鏈接是PyQt4文檔。 – ekhumoro