P
P
pornstar982019-04-27 15:03:26
Python
pornstar98, 2019-04-27 15:03:26

How to remove padding between elements in GridLayout in PyQt5?

Tried self.grid.setSpacing(0) didn't help

from PyQt5 import (QtWidgets, QtCore, QtGui)
from PyQt5.QtGui import QIcon
import sys, time


class myWindow(QtWidgets.QWidget):
    def __init__(self, parent = None):
        QtWidgets.QWidget.__init__(self, parent)
        self.grid = QtWidgets.QGridLayout()
        self.button_1 = QtWidgets.QPushButton("1")
        self.button_2 = QtWidgets.QPushButton("2")
        self.label = QtWidgets.QLabel("1")
        self.label1 = QtWidgets.QLabel("2")
        self.grid.setSpacing(0)
        self.grid.addWidget(self.button_1, 0, 0)
        self.grid.addWidget(self.label, 0, 1)
        self.grid.addWidget(self.button_2, 1, 0)
        self.grid.addWidget(self.label1, 1, 1)
        self.setLayout(self.grid)



if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = myWindow()
    window.setWindowTitle("test")
    window.resize(300, 300)
    window.show()
    sys.exit(app.exec_())

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Bezh, 2019-04-30
@pornstar98

from PyQt5 import (QtWidgets, QtCore, QtGui)
from PyQt5.QtGui import QIcon
import sys, time


class myWindow(QtWidgets.QWidget):
    def __init__(self, parent = None):
        QtWidgets.QWidget.__init__(self, parent)

        self.grid = QtWidgets.QGridLayout()

        # 1
        self.grid.setVerticalSpacing(0)
        self.grid.setContentsMargins(0, 0, 0, 0)

        self.button_1 = QtWidgets.QPushButton("1")
        self.button_2 = QtWidgets.QPushButton("2")

        # 2
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
        sizePolicy.setHeightForWidth(self.button_1.sizePolicy().hasHeightForWidth())
        self.button_1.setSizePolicy(sizePolicy)
        sizePolicy.setHeightForWidth(self.button_2.sizePolicy().hasHeightForWidth())
        self.button_2.setSizePolicy(sizePolicy)

        self.label = QtWidgets.QLabel("1")
        self.label1 = QtWidgets.QLabel("2")
        self.grid.setSpacing(0)
        self.grid.addWidget(self.button_1, 0, 0)
        self.grid.addWidget(self.label, 0, 1)
        self.grid.addWidget(self.button_2, 1, 0)
        self.grid.addWidget(self.label1, 1, 1)
        self.setLayout(self.grid)



if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = myWindow()
    window.setWindowTitle("test")
    window.resize(300, 300)
    window.show()
    sys.exit(app.exec_())

The rest is regulated by the size of the gridlayout itself by means of
self.grid.setGeometry(QtCore.QRect(80, 50, 110, 60))
in # 1, and push the grid itself into a widget, which will already be the desired window size (300, 300 in this case)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question