Display data from list in label Python

假装没事ソ 提交于 2021-02-05 11:48:26

问题


I have a list of data and the size of list is not fix. I want to display each item of this list in a label(Textview).

        self.valueT.append(value) 
        for i in self.valueT:
            // print(i)
            self.result.setText(i)

here in this code the print(i) work that display everything in console mean that it display the result but when I do self.result.setText(i) this one not working mean it did't display anything in the Label. and the second thing i want to display each value after 1sec. self.valueT is a list


回答1:


A for-loop runs so fast that our slow brains can't pick it up, so you can't see the text. The idea of executing it every T seconds helps that this is not a problem but you do not have to use a for-loop but write it using a QTimer plus an iterator, that is, it is the same logic of iterating but using the timer events:

import sys

from PyQt5 import QtCore, QtGui, QtWidgets


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

        self.label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)
        self.setCentralWidget(self.label)

        self.resize(640, 480)

        listT = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

        self.listT_iterator = iter(listT)

        self.timer = QtCore.QTimer(timeout=self.on_timeout, interval=1000)
        self.timer.start()

        self.on_timeout()

    @QtCore.pyqtSlot()
    def on_timeout(self):
        try:
            value = next(self.listT_iterator)
            self.label.setText(value)
        except StopIteration:
            self.timer.stop()


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())


来源:https://stackoverflow.com/questions/61336034/display-data-from-list-in-label-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!