显示标签Python中列表中的数据

问题描述 投票:0回答:2

我有一个数据列表,列表的大小不固定。我想在标签(Textview)中显示此列表的每个项目。

import os
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)

        path = "C:\\"
        self.retval = os.getcwd()
        os.chdir(path)
        self.retval = os.getcwd()
        self.listT1 = []

        # listT = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")

        for root, dirs, files in os.walk("."):
            self.listT1.append(os.path.basename(root))

        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.listT1)
            print(value)
            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_())

这是修改后的代码,这是我们的任务,用户转到根文件夹,它将显示标签中的每个根文件夹。但我现在这个甚至不显示显示

python python-3.x pyqt pyqt5 qlabel
2个回答
1
投票

for循环运行得如此之快,以至于我们的慢脑子无法察觉,因此您看不到文本。每T秒执行一次的想法有助于这不是问题,但是您不必使用for循环,而可以使用QTimer和一个迭代器来编写它,也就是说,这与迭代但使用计时器是相同的逻辑事件:

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

-1
投票
import time

# the position of the next label
x_postion =  0
y_position = 0
for i in self.valueT:
    label = QtWidgets.QLabel(your_window)
    label.setText(i)
    # used to stack them below each other
    label.move(x_postion, y_position)
    x_postion += 20
    # Warning: this lets the whole tread wait, so the gui won't react
    time.sleep(0.5)
© www.soinside.com 2019 - 2024. All rights reserved.