Understanding form layout mechanisms in Qt

你说的曾经没有我的故事 提交于 2019-11-27 02:57:58
Dr Deo

Layouts are actually easy to understand "i think" :)
A simple explanation of layouts can be found in the qt book "C++ Gui programming with QT 2nd edition"

What you should be aware of regarding layouts and their size policies

  • Most Qt widgets have a size policy. This size policy tells the system how the widget should stretch or shrink. Its got from the class QSizePolicy. A size policy has both vertical and horizontal components.
  • Most widgets also have a size Hint. This size hint tells the system a widgets preffered size
  • QSizePolicy has a stretch factor to allow widgets to grow at different rates

I am only familiar with 4 size policies

  • fixed size policy - The size of the widget is fixed and it can't be stretched. It remains at its size hint.
  • minimum size policy - The size hint is the smallest possible size of the widget, but it CAN STILL grow bigger if necessary.
  • Preferred size policy - the widget can shrink or grow bigger than its size hint.
  • expanding size policy - the widget can shrink or grow bigger than its size hint :)

You may want to ask,

What is the difference between preferred and expanding?
answer: Imagine a form with 2 widgets, one with preferred and another with expanding, Then any extra space will be given to the widget with the expanding policy. The widget with the preferred policy will remain at its size hint.

I recommend (WARNING: am not an expert :)) you buy and read through "C++ Gui programming with QT 2nd edition". I am currently reading it and its making alot of sense. Look at the images and see if they make some sense.

Explaining size policies

A simple example
This is a simple dialog with 2 buttons whose horizontal and vertical size policies are shown as are the horizontal and vertical stretch.

Here is the preview at its smallest size.

Here is another preview at a larger size

[EDITED: //added size hint example]

WHY SHOULD YOU CARE ABOUT SIZEHINT
You can see that every widget has a sizeHint which is vital because QT's layout system always respects the sizeHint. This is only a problem if the default size of the widget is not exactly what you want. The only way around this problem is to extend (subclass) the widget and reimplement its sizeHint() member function. An example is worth 1000 words. To save space, see my blog where there is an example project.

Shinnok

You can use QT Style Sheets to control the widgets height and other properties in an easy customizable way.

http://doc.qt.io/archives/qt-4.7/stylesheet.html

As for the layouts you need to use them wisely and strongly coupled with spacers in order to make the widgets behave exactly the way you want them to.

http://doc.qt.io/archives/qt-4.7/designer-layouts.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!