Consider this small GUI example that is supposed to display two GroupBoxes. The first one is placed in a custom QWidget:
import sys
from PyQt4 import QtGui
class SomeBoxWidget(QtGui.QWidget):
def __init__(self):
super(SomeBoxWidget, self).__init__()
#create GroupBox and layout
self.group_box = QtGui.QGroupBox("group box in widget")
self.group_box_layout = QtGui.QVBoxLayout()
self.group_box.setLayout(self.group_box_layout)
#place some stuff there
self.btn = QtGui.QPushButton("button", self)
self.group_box_layout.addWidget(self.btn)
self.main_layout = QtGui.QVBoxLayout()
self.main_layout.addWidget(self.group_box)
self.setLayout(self.main_layout)
This QWidget is placed next to a second QGroupBox that is placed directly into the main GUI layout:
class SomeGui(QtGui.QWidget):
def __init__(self):
super(SomeGui, self).__init__()
#create 2nd GroupBox and layout
self.group_box = QtGui.QGroupBox("group box in layout")
self.group_box_layout = QtGui.QVBoxLayout()
self.group_box.setLayout(self.group_box_layout)
self.btn = QtGui.QPushButton("button", self)
self.group = SomeBoxWidget()
self.group_box_layout.addWidget(self.btn)
self.main_layout = QtGui.QVBoxLayout()
self.main_layout.addWidget(self.group_box)
self.main_layout.addWidget(self.group)
self.setLayout(self.main_layout)
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = SomeGui()
app.exec_()
if __name__ == '__main__':
main()
You will notice that both QGroupBoxes are not aligned, I assume because the first one is placed inside a QWidget. How can I align them keeping the first box inside the Widget? If possible, without setting default fixed hight/width values somewhow.
Edit: I assume I need something like setContensMargins but for the outer area...
You could set the content margins of the layout of your SomeBoxWidget
container widget to 0 by adding this in your class __init__
:
self.main_layout.setContentsMargins(0, 0, 0, 0)
where the arguments of setContentsMargins are respectively the left, top, right, and bottom margins of the layout. According to the documentation:
By default, QLayout uses the values provided by the style. On most platforms, the margin is 11 pixels in all directions.
Doing the above in the code you provided results in: