简体   繁体   中英

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 . 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?

I think you eventually make a 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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