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

function print 500 values after 500 iteration function update values to listwidget

如何在每次迭代时更新 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_())