PyQt6: Removing ALL padding around widget

Question:

I’m trying push two QLineEdit-widgets all the way up to each other, but no matter how and when i call setContentsMargins(0,0,0,0) , it just does not seem to remove all margins. I’ve tried googling, but all comments just say "use layout.setContentsMargins(0,0,0,0)", and that’s it. Can somebody explain to me why this doesn’t work in my example and how to fix it?

Code:

from PyQt6.QtWidgets import QApplication, QWidget, QHBoxLayout, QLineEdit
enter image description hereimport sys

class CustomWidget(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setContentsMargins(0,0,0,0)

        self.qlineedit1 = QLineEdit()
        self.qlineedit1.setContentsMargins(0,0,0,0)

        self.qlineedit2 = QLineEdit()
        self.qlineedit2.setContentsMargins(0,0,0,0)

        self.general_layout = QHBoxLayout()
        self.general_layout.setContentsMargins(0,0,0,0)

        self.general_layout.addWidget(self.qlineedit1)
        self.general_layout.addWidget(self.qlineedit2)

        self.setLayout(self.general_layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = TimeWidget1()
    w.show()
    sys.exit(app.exec())

Window that appears:

There is clearly a gap here

Asked By: Imicoz

||

Answers:

Solution is to call layout.setSpacing(0)

Code:

from PyQt6.QtWidgets import QApplication, QWidget, QHBoxLayout, QLineEdit
enter image description hereimport sys

class CustomWidget(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.setContentsMargins(0,0,0,0)

        self.qlineedit1 = QLineEdit()
        self.qlineedit1.setContentsMargins(0,0,0,0)

        self.qlineedit2 = QLineEdit()
        self.qlineedit2.setContentsMargins(0,0,0,0)

        self.general_layout = QHBoxLayout()
        self.general_layout.setContentsMargins(0,0,0,0)

        self.general_layout.addWidget(self.qlineedit1)
        self.general_layout.addWidget(self.qlineedit2)

        self.setLayout(self.general_layout)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = TimeWidget1()
    w.show()
    sys.exit(app.exec())

Result:

No padding to speak of

Answered By: Imicoz
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.