我正在尝试将小部件添加到此流程布局中,类似于此github page中的小部件。 布局工作正常,但我要尝试的是根据先前创建的列表将小部件添加到此布局中。必须为列表中的每个项目添加一个小部件,并且其属性是根据其他列表设置的。这是代码:
class Win(QWidget):
def __init__(self):
super(Win, self).__init__()
li = ['1', '2', '3', '4']
texts = ['bowser', 'mewow', 'girk', 'huaa']
height = [30, 20, 100, 40]
width = [40, 20, 50, 120]
color = ['blue', 'red', 'green', 'yellow']
label = QLabel()
label.setObjectName('label')
flowLayout = FlowLayout()
for t in texts:
label.setText(t)
print(t)
for h in height:
label.setFixedHeight(h)
print(h)
for w in width:
label.setFixedWidth(w)
print(w)
for c in color:
label.setStyleSheet("background:" + c + ";")
print(c)
for item in li:
flowLayout.addWidget(label)
print(item)
self.setLayout(flowLayout)
这不起作用,它仅添加了一次小部件,但是似乎在添加的小部件之前保留了空间,就像它为其他小部件保留一样。是否与for循环或布局有关?
答案 0 :(得分:1)
我认为您最终会贴上标签。
至少,您应该这样写吗? 我想比较一下差异。
class Win(QtWidgets.QWidget):
def __init__(self):
super(Win, self).__init__()
li = ['1', '2', '3', '4']
texts = ['bowser', 'mewow', 'girk', 'huaa']
height = [30, 20, 100, 40]
width = [40, 20, 50, 120]
color = ['blue', 'red', 'green', 'yellow']
label = QtWidgets.QLabel()
label.setObjectName('label')
flowLayout = FlowLayout()
for l in range(len(li)):
label = QtWidgets.QLabel()
label.setObjectName('label{0}'.format(l))
label.setText(texts[l])
label.setFixedHeight(height[l])
label.setFixedWidth(width[l])
label.setStyleSheet("background:" + color[l] + ";")
flowLayout.addWidget(label)
self.setLayout(flowLayout)