我在 qt 中有一个主窗口,附加了一个选项卡小部件,其中包含一个名为“tab_upload”的选项卡。 在此选项卡上,我得到一个带有文本“流派”(它是一个库应用程序)的标签,并附有一个“加号”按钮。我希望每次单击此按钮时都能获得一个新的 QLineEdit,与其他按钮内联放置。获得正确的坐标很容易,但我无法正确设置新 QLineEdit 的几何形状。无论我在 setGeometry 函数中输入什么内容,QLineEdit 都将始终出现在中心。 而且,如果我第二次按下按钮,我会收到一条错误消息
QWidget::setLayout: 尝试在已经有布局的 QWidget“tab_upload”上设置 QLayout“”。
if(nr_genres < 4)
{
QLineEdit *newgen = new QLineEdit(ui->tab_upload);
int x = 5 + nr_genres * 90;
newgen->setGeometry(x,187,90,25);
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(newgen);
ui->tab_upload->setLayout(layout);
}
最佳答案
布局设计为have control关于小部件的定位:
All QWidget subclasses can use layouts to manage their children. The QWidget::setLayout() function applies a layout to a widget. When a layout is set on a widget in this way, it takes charge of the following tasks:
- Positioning of child widgets.
- Sensible default sizes for windows.
- Sensible minimum sizes for windows.
- Resize handling.
- Automatic updates when contents change:
- Font size, text or other contents of child widgets.
- Hiding or showing a child widget.
- Removal of child widgets.
您应该阅读this有关将小部件添加到布局的信息的文档:
- All the widgets will initially be allocated an amount of space in accordance with their QWidget::sizePolicy() and QWidget::sizeHint().
- If any of the widgets have stretch factors set, with a value greater than zero, then they are allocated space in proportion to their stretch factor (explained below).
- If any of the widgets have stretch factors set to zero they will only get more space if no other widgets want the space. Of these, space is allocated to widgets with an Expanding size policy first.
- Any widgets that are allocated less space than their minimum size (or minimum size hint if no minimum size is specified) are allocated this minimum size they require. (Widgets don't have to have a minimum size or minimum size hint in which case the stretch factor is their determining factor.)
- Any widgets that are allocated more space than their maximum size are allocated the maximum size space they require. (Widgets do not have to have a maximum size in which case the stretch factor is their determining factor.)
我认为管理布局中小部件的最简单方法是使用 Qt Creator 中的设计模式,并为每个小部件指定 minimumSize
和/或 maximumSize
,以及 sizePolicy
。这样,您就可以看到发生了什么并尝试不同的值。
关于您收到的错误,documentation for setLayout()
中提到了它。 :
If there already is a layout manager installed on this widget, QWidget won't let you install another. You must first delete the existing layout manager (returned by layout()) before you can call setLayout() with the new layout.
关于c++ - Qt 将几何图形设置为新创建的小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34704468/