Python – PyQt 4 UI freezes

pyqtpyqt4pythonqt

The following programm should just count up and int and displays its value in a label.
But after a while the GUI stops working, while the loop continous.

from PyQt4 import QtGui,QtCore
import sys

class main_window(QtGui.QWidget):
    def __init__(self,parent=None):
        #Layout       
        QtGui.QWidget.__init__(self,parent)
        self.bt=QtGui.QPushButton('crash')
        self.lbl=QtGui.QLabel('count')
        ver=QtGui.QHBoxLayout(self)
        ver.addWidget(self.bt)
        ver.addWidget(self.lbl)
        self.cnt=0
        self.running=False
        self.connect(self.bt,QtCore.SIGNAL("clicked()"),self.count)

    def count(self):
        self.running=True
        while self.running:
            self.cnt+=1
            print self.cnt
            self.lbl.setText(str(self.cnt))
            self.repaint()

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    mw=main_window()
    mw.show()
    sys.exit(app.exec_())   

Any help?

Best Answer

You're not letting Qt's event loop run, so the GUI is not responding. Also, repaint() is not needed, the QLabel.setText() will repaint the label. All it does is queue up an extra paint event, but this never gets processed.

What you need to do is replace self.repaint() with QtGui.QApplication.processEvents(). This will give the app a chance to process any pending events (including that repaint, as well as ui interaction) while you're in the loop.

Related Topic