-->

In Qt, how do I align form elements in different g

2020-08-12 02:25发布

问题:

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 QGroupBoxes.

How can I use group boxes and layouts in a way such that the QLabels and QLineEdits both inside and outside group boxes are (horizontally) aligned with each other?

Thanks!

回答1:

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.



回答2:

I don't think it'll work with sets of nested horizontal and vertical layouts. Have you considered a QGridLayout?



回答3:

kenrogers provided the solution, and here is some incomplete code that I used to get it working:

int width = 0 ;
QDialog* dialog ;
QList<QGridLayout*> layouts = dialog->findChildren<QGridLayout*>() ;
QList<QLabel*> labels ;
foreach ( QGridLayout* layout, layouts )
{
   // Loop through each layout and get the label on column 0.
   QLabel* foundLabel ;
   labels << foundLabel ;

   // Get the width.
   width = qMax( foundLabel->width(), width ) ;
}

foreach ( QLabel* label, labels )
{
   label->setMinimumWidth( width ) ;
}


回答4:

Use setGeometry() to force all your columns to the same width



标签: qt layout qt4