简体   繁体   English

在 PyQt5/Pyside2 中动态添加小部件到流布局

[英]Dynamically adding widget to flow layout in PyQt5/Pyside2

I'm trying to add widget to this flow layout similar to the one in this github page .我正在尝试将小部件添加到此流布局中,类似于此github 页面中的小部件。 The layout works perfectly but what I'm trying to do is add widget into this layout based on a previously created list.布局完美运行,但我想做的是根据先前创建的列表将小部件添加到此布局中。 A widget has to be added for every item in the list and it's properties are set according to other lists.必须为列表中的每个项目添加一个小部件,并且它的属性是根据其他列表设置的。 Here's the code:这是代码:

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)

This does not work, it just adds the widget once buts seems to leave space before the added widget like it is reserved for the other widgets.这不起作用,它只是添加了一次小部件,但似乎在添加的小部件之前留出了空间,就像它为其他小部件保留一样。 Is it something with the for loop or the layout?是for循环还是布局?

I think you eventually make a label.我认为您最终会制作 label。

At least, should you write like this?至少,你应该这样写吗? I would you like to compare the difference.我想比较一下区别。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM