pythonpyqtpyqt5qgridlayout

Trouble populating a QGridLayout


I really don't understand the reason why widget_2 and widget_3 shows up only once in this grid layout, they should appear 5 times (for the example sake) as "widget_1" (QLabel) do. I'm using a for loop and the zip() function to populate this grid layout with widgets generated inside tuples within a list called "linha", the result I'm getting is something like this:

enter image description here

I know that if I go like:

linha = [(QLabel("anything goes"), QspinBox(), QComboBox() for i in range(5)]

it'd work, but the thing is I need widgets 2 and 3 to be class attributes as the MRE presents. If you know how to help me or have any idea to make this code better please share it with us, you'll make my day

This is an MRE that you can copy and paste to run if needed

import sys
from PyQt5.QtWidgets import (QWidget, QApplication, QGridLayout,
                             QSpinBox, QComboBox, QVBoxLayout, QLabel)

class example(QWidget):

    def __init__(self):
        super().__init__()

        self.grid_layout_test()

    def grid_layout_test(self):

        layout = QVBoxLayout()
        self.widget_2 = QSpinBox()
        self.widget_3 = QComboBox()
        self.grid_layout = QGridLayout()

        lst = []

        opts = ['a', 'b', 'c', 'd', 'e']

        [self.widget_3.addItem(opt) for opt in opts]

        linha = [(QLabel("N°: " + str(i + 1)), self.widget_2, self.widget_3) for i in range(5)]
        posicoes = [(i, j) for i in range(5) for j in range(3)]

        for widgets in linha:
            for widget in widgets:
                lst.append(widget)

        for pos, ele in zip(posicoes, lst):
            self.grid_layout.addWidget(ele, *pos)

        layout.addLayout(self.grid_layout)
        self.setLayout(layout)


def main():

    app = QApplication(sys.argv)
    run = example()
    run.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

Solution

  • I really don't understand the reason why widget_2 and widget_3 shows up only once in this grid layout

    Because you have only created a QSpinBox and QComboBox, you are only copying the reference, and in the case of QGridLayout if the widget is already handled then it does not move it or create copies, I think that is what you would like but that is not how Qt works.

    A simile would be that you have 2 books (the widgets) and you place it in a closet (something like the layout), and you think that placing them in another box implies that new copies will be created.