4

我正在创建一个小部件,其中包含一个国际象棋桌和六个按钮,这些按钮显示在国际象棋桌下方的 2 行中。按钮行比棋盘宽。国际象棋表和按钮位于 QGridLayout 中。Chess table 有自己的 sizeHint,它是根据方格的大小计算出来的。

经过一些操作后,我删除了按钮并将包含所有内容的小部件调整为其 sizeHint ( resize(sizeHint()))。小部件在垂直方向上正确调整大小,但在水平方向上它保持与按钮行一样宽。问题是什么 ?

如果我仅使用国际象棋表构建小部件,则布局会正确调整小部件的大小。

我正在添加代码:

在窗口的构造函数中:

renderArea = new RenderArea(m_row,m_col,m_grid);

formLayout = new QGridLayout;

formLayout->addWidget(renderArea,0,0,1,3);

setLayout(formLayout);

在添加按钮的函数中:

addPlaneButton = new QPushButton(tr("Add plane"));
cancelButton = new QPushButton(tr("Cancel operation"));
movePlaneButton = new QPushButton(tr("Move plane"));
deletePlaneButton = new QPushButton(tr("Delete plane"));
rotatePlaneButton = new QPushButton(tr("Rotate plane"));
doneButton = new QPushButton(tr("Done"));
doneButton->setEnabled(false);

infoLabel = new QLabel(tr("Welcome to the plane editor"));
statusLabel = new QLabel();

formLayout->addWidget(statusLabel,1,0,1,3);
formLayout->addWidget(infoLabel,2,0,1,3);
formLayout->addWidget(addPlaneButton,3,0);
formLayout->addWidget(movePlaneButton,3,1);
formLayout->addWidget(deletePlaneButton,3,2);
formLayout->addWidget(rotatePlaneButton,4,0);
formLayout->addWidget(cancelButton,4,1);
formLayout->addWidget(doneButton, 4,2);

在删除国际象棋表之外的所有内容的函数中:

formLayout->removeWidget(addPlaneButton);
formLayout->removeWidget(cancelButton);
formLayout->removeWidget(movePlaneButton);
formLayout->removeWidget(deletePlaneButton);
formLayout->removeWidget(rotatePlaneButton);
formLayout->removeWidget(doneButton);
formLayout->removeWidget(infoLabel);
formLayout->removeWidget(statusLabel);


delete addPlaneButton;
delete cancelButton;
delete movePlaneButton;
delete deletePlaneButton;
delete rotatePlaneButton;
delete doneButton;


delete infoLabel;
delete statusLabel;

resize(sizeHint());

国际象棋表的 sizeHint 计算如下:

return QSize(m_rowNo*spacing, m_colNo*spacing)+QSize(31,31);
4

1 回答 1

4
  1. 您必须在修改布局的小部件后立即更新activate()其之前的布局sizeHint(),以及随后的小部件。sizeHint()

  2. 调用layout->removeWidget()是多余的。只是delete不需要的小部件。Qt 处理 QWidget 层次结构中的所有内存分配。删除 QWidget 而不告诉 Qt 端的任何人是安全的。当然也有正常的例外:例如,您不能删除其方法位于调用堆栈中某处的小部件。

  3. 如果您不想打扰调用resize(),可以在小部件的布局上设置适当的大小约束。例如:

    layout->setSizeConstraint(QLayout::SetFixedSize);

    这可确保小部件自身的大小仅足以容纳每个sizeHint().

考虑到第 1 点和第 2 点,“删除棋盘以外的所有内容”的函数可能如下所示:

void removeButtons() {
    delete addPlaneButton;
    delete cancelButton;
    delete movePlaneButton;
    delete deletePlaneButton;
    delete rotatePlaneButton;
    delete doneButton;
    delete infoLabel;
    delete statusLabel;

    formLayout->activate();
    resize(sizeHint());
}
于 2012-06-18T22:40:48.833 回答