1
votes

I'm running into a bit of a program with an interface I'm designing. It's a bit hard to concisely explain the problem, so I'll introduce the elements at play first. I have a QMainWindow MainWindow that has QWidget MainWidget as central widget. MainWidget contains two widgets: A QLabel and QWidget SubWidget. SubWidget contains a mere QLabel.

Better illustrated (I hope I represented inheritance correctly. Either way, MainWindow inherits from QMainWindow, etc.):

form (MainWindow::QMainWindow)
|main_widget (MainWidget::QWidget)
||label_1 (QLabel)
||sub_widget (SubWidget::QWidget)
|||label_2 (QLabel)

The problem lies herein; the label inside SubWidget has an offset to the right. An image can be found here.

The code is fairly straightforward. I tried to condense it as much as I could.

import sys
from PySide.QtCore import *
from PySide.QtGui import *

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.main_widget = MainWidget(self)

        self.setCentralWidget(self.main_widget)

class MainWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.label_1 = QLabel("Label 1")

        self.sub_widget = SubWidget()

        self.layout = QVBoxLayout()  # Vertical layout.
        self.layout.addWidget(self.label_1)
        self.layout.addWidget(self.sub_widget)

        self.setLayout(self.layout)

class SubWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.label_2 = QLabel("Label 2")

        self.layout = QHBoxLayout()  # Horizontal layout.
        self.layout.addWidget(self.label_2)

        self.setLayout(self.layout)

def main():
    app = QApplication(sys.argv)
    form = MainWindow()
    form.show()
    app.exec_()

if __name__ == "__main__":
    main()

The obvious solution would be to put label_2 in MainWidget, but that conflicts with what I want to do. What causes the weird offset? Is there anything I can do to combat it?

Thank you very much!

1

1 Answers

1
votes
self.layout.setContentsMargins(0, 0, 0, 0)

in SubWidget.

http://doc.qt.io/qt-5/qlayout.html#contentsMargins