简体   繁体   English

Qt在布局中自动排列小部件

[英]Qt Auto-arrange widgets in layout

I'm new to Qt and have a problem that I haven't been able to solve. 我是Qt的新手,有一个我无法解决的问题。

What I have is a scroll area that I add widgets to (what the widgets are doesn't matter). 我所拥有的是一个滚动区域,我添加了小部件(小部件无关紧要)。 Each of the widgets has a static size and they all have the same width (this might be important). 每个小部件都有一个静态大小,它们都具有相同的宽度(这可能很重要)。 What I'm trying to do is to have a layout/setup such that all these widgets are displayed on the scroll area horizontally until there is not enough room for another widget, at which point it starts putting the widgets on a new row, continuing until there are none left. 我要做的是设置一个布局/设置,使所有这些小部件水平显示在滚动区域上,直到没有足够的空间容纳另一个小部件,此时它开始将小部件放在一个新行上,继续直到没有人离开。

I've thought about ways to implement this manually, but I feel like this is something that Qt already supports and I just haven't been able to find the documentation on it. 我已经考虑过手动实现这个的方法,但我觉得这是Qt已经支持的东西,我只是无法找到它的文档。

You can see the Flow Layout Example . 您可以看到Flow Layout示例 It demonstrates a custom layout that arranges child widgets from left to right and top to bottom. 它演示了一个自定义布局,可以从左到右,从上到下排列子窗口小部件。 The items are first laid out horizontally and then vertically when each line in the layout runs out of space. 首先,当布局中的每一行都没有空间时,项目首先水平布局,然后垂直布局。

The FlowLayout class inherits QLayout . FlowLayout类继承QLayout It is a custom layout class that arranges its child widgets horizontally and vertically. 它是一个自定义布局类,可以水平和垂直排列其子窗口小部件。 You can implement it as shown in the link and create a custom widget that holds the flow-layout and set that as the QScrollArea 's widget. 您可以如链接中所示实现它,并创建一个包含流布局的自定义窗口小部件,并将其设置为QScrollArea的窗口小部件。

scrollArea->setWidgetResizable(true); // Important or else the widget won't expand to the size of the QScrollArea, resulting in the FlowLayout showing up as a vertical list of items rather than a flow layout
scrollArea->setWidget(new CustomWidget);

In the constructor of CustomWidget : CustomWidget的构造函数中:

// Create FlowLayout
FlowLayout *flowLayout = new FlowLayout;

// Populate FlowLayout with your widgets
for (int i=0; i<n; i++) 
{
    ...
    flowLayout->addWidget(widget);
}

setLayout(flowLayout);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM