Search code examples
pythonpython-3.xpyqt4

How can I stop printing numbers clicking on a pushbutton


I want to start printing numbers in a GUI in pyqt4 but when I pressed the start button it freezes and I have to close de window, I want start the psocess clicking on a button and stoped with another button, here I let my code

This is the part where I tried to start and stop the process

class LecturaFrecuencia(QMainWindow):
    """docstring for LecturaFrecuencia"""
    def __init__(self, parent):
        super(LecturaFrecuencia, self).__init__(parent)
        uic.loadUi('frecuencia.ui', self)
        global START
        self.button_volver.clicked.connect(self.regresar)
        self.button_terminar.clicked.connect(self.terminar_monitoreo)
        self.button_guardar.clicked.connect(self.guardar)
        self.button_iniciar.clicked.connect(self.iniciarLectura)

    def iniciarLectura(self):
        START = 1
        while START :
            pqrst= random.randint(55,101)
            time.sleep(1.0)
            print(str(pqrst))
            self.pqrst.setText(str(pqrst))
            if self.button_terminar.isChecked():
                START = 0
            else:
                pass

Solution

  • Never use time.sleep() in the GUI thread since it will freeze it. If you want to do periodic tasks use a QTimer:

    import random
    from PyQt4 import QtCore, QtGui, uic
    
    class LecturaFrecuencia(QtGui.QMainWindow):
        """docstring for LecturaFrecuencia"""
        def __init__(self, parent=None):
            super(LecturaFrecuencia, self).__init__(parent)
            uic.loadUi('frecuencia.ui', self)
    
            timer = QtCore.QTimer(
                self,
                interval=1000,
                timeout=self.processing
            )
    
            self.button_iniciar.clicked.connect(timer.start)
            self.button_terminar.clicked.connect(timer.stop)
    
        @QtCore.pyqtSlot()
        def processing(self):
            pqrst = random.randint(55,101)
            self.pqrst.setText("{}".format(pqrst))
    
    if __name__ == '__main__':
        import sys 
        app = QtGui.QApplication(sys.argv)
        w = LecturaFrecuencia()
        w.show()
        sys.exit(app.exec_())