gpt4 book ai didi

python - 函数在 500 次迭代后打印 500 个值函数更新值到 listwidget

转载 作者:行者123 更新时间:2023-12-01 07:37:30 26 4
gpt4 key购买 nike

如何在每次迭代时更新 listwidget ?它在 500 次迭代后更新 listwidget。pyqt4、python3.7

def input_val(self):

for i in range(500):

time.sleep(1)
self.listWidget.addItem(str(i))
print(i)

最佳答案

您不应该在主线程中使用 sleep(),因为它会阻塞 GUI 事件循环,如果您想执行周期性任务,那么您应该使用 QTImer。

根据上述解决方案是:

from PyQt4 import QtCore, QtGui


class Timer(QtCore.QObject):
timeout = QtCore.pyqtSignal(int)
finished = QtCore.pyqtSignal()

def __init__(self, parent=None, **kwargs):
self._maximum = kwargs.pop("maximum", 0)
_interval = kwargs.pop("interval", 0)
_timeout = kwargs.pop("timeout", None)
_finished = kwargs.pop("finished", None)

if parent is not None:
kwargs["parent"] = parent
super(Timer, self).__init__(**kwargs)
self._counter = 0
self._timer = QtCore.QTimer(timeout=self._on_timeout)
self.interval = _interval
if _timeout:
self.timeout.connect(_timeout)
if _finished:
self.timeout.connect(_finished)

@QtCore.pyqtSlot()
def start(self):
self._timer.start()

@property
def interval(self):
return self._timer.interval()

@interval.setter
def interval(self, v):
self._timer.setInterval(v)

@property
def maximum(self):
return self._maximum

@maximum.setter
def maximum(self, v):
self._maximum = v

@QtCore.pyqtSlot()
def _on_timeout(self):
self.timeout.emit(self._counter)
self._counter += 1
if self._counter >= self.maximum:
self.finished.emit()
self._timer.stop()


class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)

self.m_listwidget = QtGui.QListWidget()
self.setCentralWidget(self.m_listwidget)

t = Timer(self, maximum=500, interval=1000, timeout=self.onTimeout)
t.start()

@QtCore.pyqtSlot(int)
def onTimeout(self, i):
self.m_listwidget.addItem(str(i))


if __name__ == "__main__":
import sys

app = QtGui.QApplication(sys.argv)

w = MainWindow()
w.show()

sys.exit(app.exec_())

关于python - 函数在 500 次迭代后打印 500 个值函数更新值到 listwidget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56918025/

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