I'm trying to create a standard two-column form, where the first column is a text label (QLabel
) and the second column is an interactive widget, typically a text field (QLineEdit
). We have decided to place form rows that share a common theme inside a QGroupBox
, and thus in a separate layout than the main layout. Thus, the form elements inside each QGroupBox
do not horizontally align with the form elements outside of the QGroupBox
es.
How can I use group boxes and layouts in a way such that the QLabel
s and QLineEdit
s both inside and outside group boxes are (horizontally) aligned with each other?
Thanks!
Group boxes are container widgets that organize buttons into groups, both logically and on screen. They manage the interactions between the user and the application so that you do not have to enforce simple constraints. Group boxes are usually used to organize check boxes and radio buttons into exclusive groups.
A group box provides a frame, a title on top, a keyboard shortcut, and displays various other widgets inside itself. The keyboard shortcut moves keyboard focus to one of the group box's child widgets. QGroupBox also lets you set the title (normally set in the constructor) and the title's alignment.
To set size column You can use setColumnMinimumWidth() , but You also must manipulate setSizePolicy for each element in column as QLabel, QGroupBox etc, because policy determines how behavior must be particular object in column.
You can set the minimumWidth property on all of the labels inside the groupboxes to something that is just wide enough to display the widest label. That will get all of the labels inside the different group boxes aligned.
Now, to get the labels outside of the groupboxes aligned with those inside: First, I assume that each label/lineedit pair is in its own horizontal layout, or that you have multiple rows inside of a grid. In either case, what you can do is set the minimumWidth of the labels to the same value as the labels in the groupboxes. Finally, adjust the layoutLeftMargin, layoutRightMargin, and layoutSpacing properties on the horizontal (or grid) layout until the right and left edges of the label/lineedit pair align with those inside the groupboxes.
If you're not already using the Form Editor in Qt Creator, or Qt Designer, to build your UI, I found it to make this task fairly easy.
I have to admit, this feels a little kludgey, but in the simple test case I built, it seemed to work okay. On the other hand, this seems likely to break if the user changes the font size. Maybe there's a better way?
Hope this helps.
I don't think it'll work with sets of nested horizontal and vertical layouts. Have you considered a QGridLayout?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With