PyQt 4 UI 冻结
以下程序应该只是累加和 int 并在标签中显示其值。 但过了一会儿,GUI 停止工作,而循环继续。
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_())
有什么帮助吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您没有让 Qt 的事件循环运行,因此 GUI 没有响应。另外,不需要
repaint()
,QLabel.setText()
将重新绘制标签。它所做的只是排队一个额外的绘制事件,但这永远不会被处理。您需要做的是将
self.repaint()
替换为QtGui.QApplication.processEvents()
。这将使应用程序有机会在您处于循环中时处理任何待处理事件(包括重绘以及 UI 交互)。You're not letting Qt's event loop run, so the GUI is not responding. Also,
repaint()
is not needed, theQLabel.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()
withQtGui.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.你有没有想过从这个无限循环中退出?例如
self.running=False
。GUI 可能会停止工作,因为它没有足够的时间来执行
重绘
。您可能需要在循环中添加一些time.sleep
来等待 GUI 重新绘制。更新:您应该使用QTimer,而不是一个简单的 while 循环,用于您正在实现的行为。
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 sometime.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.