Search code examples
pythonpyqtqwidgetpyqt6qlayout

PyQt6: Removing ALL padding around widget


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


Solution

  • 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