我正在使用Python 3和Qt5。 我设计了一个QWidget,只有700多个QLabel。我需要更改它们,但我想这样做而不必写超过700行来为我的所有标签设置文本。 我还需要随意展示和隐藏它们。
如果我有一个该变量名称的字符串,是否可以对它们进行分组或编辑变量? 我正在寻找类似Matlab'assignin'功能的东西。
标签名为label_A - label_Z和label_AA - label_ZZ
来自主课程 导入ezodf
self.ui = AnalysisGui.Ui_Form()
self.ui.setupUi(self)
self.Alphabet = ["a", "b", "c", "d", "e",
"f", "g", "h", "i", "j",
"k", "l", "m", "n", "o",
"p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z"]
for Alpha in self.Alphabet:
self.ui.findChild(QtGui.QLabel, "label_"+Alpha.upper()).SetText(Alpha.upper()+" ")
for Beta in self.Alphabet:
self.ui.findChild(QtGui.QLabel, "label_"+Alpha.upper()+Beta.upper()).SetText(Alpha.upper()+Beta.upper()+" ")
这是来自AnalysisGui类,显示了如何定义标签
self.label_A = QtGui.QLabel(Form)
self.label_A.setStyleSheet(_fromUtf8("color: rgb(0, 0, 0);\n""font: 8pt \"Calibri\";\n""background-image: url(:/Thoth/SeeThrough.png);"))
self.label_A.setObjectName(_fromUtf8("label_A"))
self.gridLayout.addWidget(self.label_A, 1, 0, 1, 1)
self.label_B = QtGui.QLabel(Form)
self.label_B.setStyleSheet(_fromUtf8("color: rgb(0, 0, 0);\n""font: 8pt \"Calibri\";\n""background-image: url(:/Thoth/SeeThrough.png);"))
self.label_B.setObjectName(_fromUtf8("label_B"))
self.gridLayout.addWidget(self.label_B, 1, 1, 1, 1)
self.label_C = QtGui.QLabel(Form)
self.label_C.setStyleSheet(_fromUtf8("color: rgb(0, 0, 0);\n""font: 8pt \"Calibri\";\n""background-image: url(:/Thoth/SeeThrough.png);"))
self.label_C.setObjectName(_fromUtf8("label_C"))
self.gridLayout.addWidget(self.label_C, 1, 2, 1, 1)
感谢您的帮助。
答案 0 :(得分:0)
您可以尝试使用QWidget.findChild
import sys
from PyQt4.QtGui import *
try:
from PyQt4.QtWidgets import *
except ImportError:
pass
app = QApplication(sys.argv)
window = QWidget()
layout = QVBoxLayout()
for i in range(26):
title = chr(ord('A')+i)
label = QLabel(title, window)
label.setObjectName("label_"+title)
layout.addWidget(label)
window.findChild(QLabel, "label_F").setText("test")
window.setLayout(layout)
window.show()
app.exec_()