Skip to content

Advanced Qt layouts

Wednesday, 30 November 2005  |  Geiseri

One of the cool things about Qt that seems to be ignored is the QLayout classes. Most of us are content to use simple things like QHBox and QVBox layouts to get what we want. But what happens when you need more complex behavior? Well the trolls gave us the ability to create new layouts with a trivial amount of code...

One example could be some sort of touch screen menu. Well in this case there is a center object that has a whats this description of a menu item. Then there are buttons that should flow around it. One approach could be to hard code this. The problem here is when the touch screen updates from 800x600 to 1024x768 your screen will look funny. Worse, if you need to dynamicly add and remove buttons, the problem is more cumbersome. The other approach is to use Qt's awesome layout engine.

I basicly subclassed QLayout and made my own layout function that would position the widgets around a central widget. This way I could just create my controls and place them on the layout as I pleased: ArcLayout *arc = new ArcLayout(this, 6, 6); for( int idx = 0; idx < maxbuttons; ++idx) { QFrame *button = new QFrame(this); button->resize(200,50); button->setFrameStyle(QFrame::Box|QFrame::Plain); button->setLineWidth(4); button->setMidLineWidth(3);

	arc->addWidget(button);
	m_buttons.append(button);

}
QFrame *blah = new QFrame(this);
blah->setFrameStyle(QFrame::Box|QFrame::Plain);
blah->setLineWidth(4);
blah->setMidLineWidth(3);
blah->resize(150,150);
blah->lower();
arc->setFocusWidget(blah);

This gave me this: [image:1655]

This is a simple case, but I think this shows the possibilities of what Qt can do. Ironicly I spent longer on this blog entry than I did writing this layout, so we can see how simple this is. Now if only Qt designer could handle custom layouts ;)