How to push widgets to top left instead of bottom right

2.4k views Asked by At

Just started messing with pyqt5 and was wondering how to push the widgets to top for QVBoxLayout and left for QHBoxLayout. Currently with addStretch() it pushes the widgets to bottom/right. I'd like to avoid using absolute positioning.

self.tabColor.layout = QVBoxLayout(self)
self.tabColor.layout.addStretch()    

## FOR CONTROL
lbl_control = QLabel(self)
lbl_control.setText("control")
le_control = QLineEdit(self)

hbox_control = QHBoxLayout()
hbox_control.addStretch(1)
hbox_control.addWidget(lbl_control)
hbox_control.addWidget(le_control)

## FOR UNKNOWN
lbl_unknown = QLabel(self)
lbl_unknown.setText("unknown")
le_unknown = QLineEdit(self)

hbox_unknown = QHBoxLayout()
hbox_unknown.addStretch(1)
hbox_unknown.addWidget(lbl_unknown)
hbox_unknown.addWidget(le_unknown)


self.tabColor.layout.addLayout(hbox_control)
self.tabColor.layout.addLayout(hbox_unknown)
self.tabColor.setLayout(self.tabColor.layout)

I used self.tabColor.layout.setDirection(3). It places the horizontal layout on top but it seems to flip the order. Basically 'unknown' will be first then 'conrol'. Its not a big deal but was wondering if there are other options i could try

2

There are 2 answers

0
Aleš Erjavec On

Change the order of addWidget/Stretch calls (i.e. add the stretch after the widget)

0
yurisnm On

The first approach I'd recommend you would also be to set the direction of your layout, since you are trying to have another way:

  1. Try adding always in the beginning, instead of adding widget trying inserting it

instead of:

self.layout.addWidget(self.lbl_1)
self.layout.addWidget(self.lbl_2)
self.layout.addWidget(self.lbl_3)

try:

self.layout.insertWidget(0,self.lbl_1)
self.layout.insertWidget(0,self.lbl_2)
self.layout.insertWidget(0,self.lbl_3)

and it'll be added in the opposite direction, the widgets that are already inside your layout will be shifted according to your layout QHBoxLayout, or QVBoxLayout.