In today’s post I’m sharing with you a rather obscure way of enabling auto resize for widgets in a window derived from QDialog. The fact that it is obscure is what warrants the need for this post, so let’s put together a small window using Qt Creator:
A dialog window assembled with Qt Creator. Everything looks fine…
As you can see, it all looks fine, but as soon as I resize the window, I get this:
Same window after increasing its size (please consider image scaling on the website)
Obviously, there is an issue. To avoid such a nasty thing from happening, one would think (as I did) that there is a button shortcut in Creator or a property that can be set fix all this, but as it turnes out there isn’t. According to the Qt documentation, the recommended (and seems to me the only) way to turn on auto resize for widgets, is to apply a layout on your window. What is even more interesting, is that there is only a very tiny, barely noticeable indication that something has changed. Let’s examine the object tree of the dialog window before and after applying the layout to the window:
The object tree before and after applying a layout to the window itself
If you didn’t notice the difference from first glance, I’m not surprised. Please look again and notice the small crossed out circle going missing on the icon of the QDialog object after applying the layout. That is all the indication you will get graphically. By examining the .ui file however, we see a more conspicuous change. This is the code before applying the layout:
Qt .ui XML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <!-- ... --> <property name="windowTitle"> <string>Dialog</string> </property> <widget class="QWidget" name=""> <property name="geometry"> <rect> <x>10</x> <y>10</y> <width>471</width> <height>351</height> </rect> </property> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QTableView" name="tableView"/> </item> <!-- ... -->
And this is after:
Qt .ui XML
1 2 3 4 5 6 7 8 9 10 11 <!-- ... --> <property name="windowTitle"> <string>Dialog</string> </property> <layout class="QVBoxLayout" name="verticalLayout_2"> <item> <layout class="QVBoxLayout" name="verticalLayout"> <item> <widget class="QTableView" name="tableView"/> </item> <!-- ... -->
QVBoxLayout object has been added with the name of
verticalLayout2, while a bunch of hard coded size info has been removed. Obviously, after applying this change, everything is as it should be, the widgets resize with the window, so all is well.
I wish this option would somehow be implemented in a more self-explanatory manner, but let this be the greatest inconvenience with Qt and Creator.
Anyway, lesson learned:
Apply a layout to the window in order to enable automatic widget resize.