Advertisement
furas

Python - PyQt5 - Timer (reddit.com)

Oct 26th, 2016 (edited)
1,212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. # author: Bartlomiej "furas" Burek (https://blog.furas.pl)
  2. # 2016.10.26
  3. # https://www.reddit.com/r/learnpython/comments/59gzue/pyqt5_time_library_while_loop_freezes_window/
  4. # http://pastebin.com/eDeMdrAA
  5.  
  6. import sys, time
  7. from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit, QRadioButton, QPushButton
  8. from PyQt5.QtGui import QIcon, QFont
  9. from PyQt5.QtCore import QTimer
  10.  
  11. class Widget(QWidget):
  12.    
  13.     def __init__(self, parent=None):
  14.         QWidget.__init__(self, parent)
  15.  
  16.         self.widget_layout = QVBoxLayout()
  17.  
  18.         # Making buttons
  19.         self.radio1 = QPushButton('Radio 1')
  20.         self.radio2 = QPushButton('Radio 2')
  21.  
  22.         # Making the text window
  23.         self.line_edit = QLineEdit()
  24.         font = self.line_edit.font()
  25.         font.setPointSize(32)
  26.         self.line_edit.setFont(font)
  27.  
  28.         # When the buttons get clicked
  29.         self.radio1.clicked.connect(self.radio1_clicked) #[bool] makes it a toggle button?
  30.         self.radio2.clicked.connect(self.radio2_clicked)
  31.  
  32.         # Place the buttons and line edit onto the screen.
  33.         self.widget_layout.addWidget(self.radio1)
  34.         self.widget_layout.addWidget(self.radio2)
  35.         self.widget_layout.addWidget(self.line_edit)
  36.         self.setWindowTitle('While loop test')  # Window name
  37.         self.setWindowIcon(QIcon('violin.png'))  # Icon used by the window.
  38.         self.setLayout(self.widget_layout)
  39.  
  40.         self.test = 0
  41.         self.timeout = time.time() + 60*5 # 5 minutes from now
  42.         self.timer = QTimer()
  43.         self.timer.timeout.connect(self.update_time)
  44.         self.timer.start(1000)
  45.        
  46.     def radio1_clicked(self):
  47.         self.line_edit.setText('Radio 1')
  48.  
  49.     def radio2_clicked(self):
  50.         self.line_edit.setText('Radio 2')
  51.  
  52.     def update_time(self):
  53.         if self.test == 5 or time.time() > self.timeout:
  54.             self.timer.stop()
  55.             return
  56.         self.test += 1
  57.         widget.line_edit.setText(str(self.test))
  58.  
  59. if __name__ == '__main__':
  60.   app = QApplication(sys.argv)
  61.   widget = Widget()
  62.   widget.show()
  63.   #widget.line_edit.setText('Text updated!')
  64.   sys.exit(app.exec_())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement