The Linux Page

QWidget not appearing without a Layout

I got a problem with Qt that took me a whole day to fix!

I created a widget with many children. At first I used the QVBoxLayout and QHBoxLayout to lay out the child buttons in a grid like layout without paying much attention to the details. This was not too bad except that somehow the system picked up the smallest possible size for each button. Once I put a minimum size, it was better, but still not giving me much control in comparison to the specification for my project.

So at that point I looked around to learn how to create your own layout. Got the idea to look at the existing layout implementations (QBoxLayout). Darn! Hundreds of lines of code. Probably necessary, but that was not what I was looking for. My layout code shouldn't much more than one page.

At that point, I search on the net and found the page about Qt 4.7: Layout Management. That page includes an example (at the bottom) which at least is a lot smaller, but again does not really match what I'm looking for. However, they talked about Manual Layout. That sound exciting.

The Manual Layout starts by implementing your own resizeWidget() function (an overload,) although there are a few problems with that in my case, it worked. That is, the function was being called and I could (finally!!!!) find the size of the area where my widget sits.

QRect rect = parentWidget()->geomertry();

This rectangle includes our widget width and height (the x and y positions are not necessary since all our children start at (0, 0) from our top-left corner.

Now that I have the size I can compute all the children widget sizes and positions. So I write a simple loop to place everything in a grid, all children with exactly the same size. I start the app. NOTHING.

I try all sorts of things, still nothing.

Finally, I decide that I may actually have to create my own layout. At that point I look at my loop creating the children widgets and... I notice that I create the children without a Parent widget. Argh! Without a parent the children are not rendered since they are no where.

I add the parent to the widget, restart the application, et voilà! That works.

So, the Manual Layout using a resizeEvent() implementation of your own works. Just make sure the children are indeed children. Why was it working with the QVBoxLayout and QHBoxLayout is because layout objects re-parent widgets assigned to them as otherwise expected by the system.