Osama Billah
Osama Billah

Reputation: 101

Display data from list in label Python

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

Upvotes: 0

Views: 1904

Answers (1)

eyllanesc
eyllanesc

Reputation: 244212

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_())

Upvotes: 1

Related Questions