在QT中,如何在自定义小部件中定义布局的几何形状

In QT, How to define the geometry for the Layout in a custom Widget

本文关键字:定义 布局 几何形 自定义 QT 小部      更新时间:2023-10-16

在自定义QWidget(例如MyWidget)中,我包含了一个管理子部件的布局:

MyWidget window;
QPushButton button;
QVBoxLayout layout(window);
layout.addWidget(button);
window.show();

我希望布局是在一个特定的位置和大小,默认情况下,QWidget将其设置为整个几何。

我如何设置layout将考虑管理他的空间的几何?

作为间接疑问句:布局使用哪个函数来设置子几何?

QPushButton *button = new QPushButton;
verticalLayout->addSpacing(300);
verticalLayout->addWidget(button);
button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
button->setMinimumSize(500, 200);
button->setMaximumSize(500, 200);

如果您需要垂直和水平间距-使用QGridLayout

QLayout使用两者的摘要作为页边距:

  • 父部件内容页边距
  • 布局内容页边距
解决方案是在自定义小部件构造函数中将内容边距设置为所需的值。在创建布局时,将其内容边距设置为0。
this->setContentsMargins(left, top, right, bottom);
// ...
layout->setContentsMargins(0,0,0,0);

Layout setGeometry由QWidget resize事件调用,并根据它设置子部件的大小。由于并非所有函数都是虚函数,因此不可能(或至少很难)修改这种行为。