Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Make Qt Grid Layout Auto Size Column Widths

I have a QDialog with a grid layout in it. The grid is 5 columns wide by a variable number of rows. The QDialog begins with a prebuilt UI that has a label in each of the 5 columns. The rest of the grid is built as follows. For each row added:

  • a QLineEdit is added to col 0
  • a QComboBox is added to cols 1-3 and each has a variable and different number of items
  • a QCheckBox is added to col 4

When this is complete column 0 is the widest column. Columns 1-4 are the same width. Some combo box items (cols 1-3) are too wide to see and show up as "...". The check box column (4) is wider than it needs to be. I've tried using QWidget::adjustSize() on every damn widget in there including the dialog itself and I can't get it to auto size to fit everything. In trying to debug it I printed out the widget's width for each column but the values I'm seeing are no way what I'm seeing on screen. I was under the impression the grid layout would automatically adjust each widget in each column to be just wide enough to fit the widest item but it doesn't seem to be doing that. Is there some sort of setAutoColumnWidth property or something?

like image 764
Qman Avatar asked Jan 06 '15 22:01

Qman


1 Answers

If you want to set widths for layout columns, you can set the Stretch values for the widgets inside the layout. For example set the horizontal stretches of all the widgets to 1 for equal widths :

lineEdit->sizePolicy().setHorizontalStretch(1);
comboBox1->sizePolicy().setHorizontalStretch(1);
comboBox2->sizePolicy().setHorizontalStretch(1); 
comboBox3->sizePolicy().setHorizontalStretch(1); 
checkBox->sizePolicy().setHorizontalStretch(1);

If you want a specific column to be wider, set a higher stretch value for the widget in that column.

like image 167
Nejat Avatar answered Oct 12 '22 05:10

Nejat