【问题标题】:Dynamically adding widget to flow layout in PyQt5/Pyside2在 PyQt5/Pyside2 中动态添加小部件到流布局
【发布时间】:2020-06-22 11:06:52
【问题描述】:

我正在尝试将小部件添加到此流布局中,类似于 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 循环还是布局?

【问题讨论】:

    标签: python pyqt5 pyside2


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-23
      • 2012-06-03
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 2014-10-17
      相关资源
      最近更新 更多