PyQt 4 UI freezes

The following program should simply count and enter and display its value in the label. But after some time, the graphical interface stops working, and the cycle is continuous.

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?

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

Have you thought about any way out of this endless cycle? For example. self.running=False.
The GUI may stop working because it does not have enough time to execute repaint. You might want to add in a loop time.sleepto wait for the graphical interface to be redrawn.

.. QTimer, while, , .

+4

Qt, . , repaint() , QLabel.setText() . , , - , .

, self.repaint() QtGui.QApplication.processEvents(). ( , ui), .

+6

, .

+2

Source: https://habr.com/ru/post/1726188/


All Articles