gpt4 book ai didi

python - 创建不锁定窗口的循环Pyqt4

转载 作者:行者123 更新时间:2023-11-28 21:26:50 24 4
gpt4 key购买 nike

我使用的是 PyQt4,我创建了一个带有切换按钮的窗口。当我选择按钮时,我想启动一个循环以尽快更新屏幕。目前,它锁定了我的窗口,我无法再次选择按钮来关闭循环甚至移动窗口。我希望找到一种无需线程即可执行此操作的方法。我无法发布我的实际代码,但这基本上就是我现在所拥有的。

self.connect(self.pushButton,SIGNAL("toggled(bool)"),self.testLoop)

def testLoop(self, bool):
while bool:
print "looping"

最佳答案

您采用的方法主要取决于循环执行的任务的性质。

如果您可以将任务分解成非常小的步骤,则可以简单地使用计时器启动循环,然后调用 processEvents。在更新您的图形用户界面的每一步:

from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.label = QtGui.QLabel('Count = 0', self)
self.button = QtGui.QPushButton('Start', self)
self.button.clicked.connect(self.handleButton)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.label)
layout.addWidget(self.button)
self._active = False

def handleButton(self):
if not self._active:
self._active = True
self.button.setText('Stop')
QtCore.QTimer.singleShot(0, self.runLoop)
else:
self._active = False

def closeEvent(self, event):
self._active = False

def runLoop(self):
from time import sleep
for index in range(100):
sleep(0.05)
self.label.setText('Count = %d' % index)
QtGui.qApp.processEvents()
if not self._active:
break
self.button.setText('Start')
self._active = False

if __name__ == '__main__':

import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())

关于python - 创建不锁定窗口的循环Pyqt4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12200274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com