在 运行 时间创建具有动态名称的 Qlabel

creating Qlabels with dynamic name at run time

#in this example len(list) is 5

i=0
while i < len(list):
    label=q_label_i                 #creating a name for the label
    self.label=QLabel()             #
    grid.addWidget(self.label,i ,0)     # grid is a grid = QGridLayout()
    i=i+1

上面的代码创建了 5 个标签,但是它们都被称为 q_label_i 而不是 q_label_0 q_label_1 .... q_label_4

在另一个函数中 - 我将从文件中读取数据并更新这些标签并将它们引用为 q_label_0 q_label_1 .... q_label_4

我们将不胜感激任何有关如何让它发挥作用的提示。

您必须处理两个 个名称。 qlabel 绑定的变量名和 Qt 使用的 objectName

处理可变数量的项目时,通常最好将它们存储在字典或列表中

self.labels = dict()
for i in range(5):
    name = 'q_label_{}'.format(i)
    label = QLabel()
    label.setObjectName(name)
    grid.addWidget(label, i, 0)
    self.labels[name] = label

稍后,当您想要引用标签时,只需执行

self.labels['q_label_2']