开发者

PyQt 4 UI freezes

开发者 https://www.devze.com 2022-12-14 07:16 出处:网络
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.

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?


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.


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 exit from this endless loop? E.g. self.running=False.
GUI may stop working because it doesn't have enough time to perform repaint. You may want to add some time.sleep in the loop to wait for the GUI to repaint.

Upd.: You should use QTimer, not a simple while loop, for the behavior you're implementing.


You have to let the main event loop run, something you're not doing.

0

精彩评论

暂无评论...
验证码 换一张
取 消