Search code examples
pythonuser-interfacepyqtpyqt5pygui

Reduce spacing in PyQt5 - GridLayout - Between the widgets


I am new to PyQt5, I created a grid layout as shown in figure I want to reduce the gap between the three widgets, I tried playing around margins, spacing and row stretch but none have worked, Please look ar the image in hyperlink and help me :

Image: Image

def createlayout(self):
    self.label1=QLabel(self.label,self)
    self.label2=QLabel(self.label2,self)
    self.label3 = QLabel("try", self)
    self.textbox = QLineEdit(self)

    vbox=QGridLayout()


    vbox.addWidget(self.label1,0,0,1,1)

    vbox.addWidget(self.textbox,1,0,1,1)

    vbox.addWidget(self.label2,2,0,1,1)

    vbox.addWidget(self.label3, 3, 0, 1, 1)

    vbox.setContentsMargins(1,0,0,0)
    #vbox.setAlignment('AlignCenter')
    vbox.setRowStretch(0, 0)
    vbox.setRowStretch(1, 0)
    vbox.setRowStretch(2,0)
    vbox.setColumnStretch(1,0)
    #vbox.setRowStretch(2,1)
    vbox.setRowStretch(3,0)
    vbox.setSpacing(0)

Solution

  • QGridLayout::setRowStretch(int row, int stretch)

    Sets the stretch factor of row row to stretch. The first row is number 0.

    The stretch factor is relative to the other rows in this grid. Rows with a higher stretch factor take more of the available space.

    The default stretch factor is 0. If the stretch factor is 0 and no other row in this table can grow at all, the row may still grow.

    import sys
    from PyQt5.Qt import *
    
    class Window(QWidget):
        def __init__(self):
            super().__init__()
            self.createlayout()
    
        def createlayout(self):
            self.label1 = QLabel("self.label")
            self.label2 = QLabel("self.label2")
            self.label3 = QLabel("try", )
            self.textbox = QLineEdit()
    
            vbox = QGridLayout(self)
            vbox.addWidget(self.label1, 0, 0)
            vbox.addWidget(self.textbox, 1, 0)
            vbox.addWidget(self.label2, 2, 0)
            vbox.addWidget(self.label3, 3, 0)
            
            vbox.setRowStretch(4, 1)                                 # +++
    
            
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        w = Window()
        w.resize(300, 200)
        w.show()
        sys.exit(app.exec_())
    

    enter image description here