layout sizeHint qwidget

时间:2012-06-18 16:11:34

标签: qt qgridlayout

我正在创建一个小部件,其中包含一个国际象棋桌和六个按钮,这些按钮显示在国际象棋桌下方的两行中。按钮行比国际象棋桌宽。国际象棋桌和按钮位于QGridLayout中。国际象棋桌有自己的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);

1 个答案:

答案 0 :(得分:4)

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

    < / LI>
  2. layout->removeWidget()的调用是多余的。只需delete不需要的小部件。 Qt处理QWidget层次结构中的所有内存分配。删除QWidget而不告诉任何人关于Qt的事情是安全的。当然有一些理智的例外:例如,您无法删除其方法位于调用堆栈某处的窗口小部件。

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

    layout->setSizeConstraint(QLayout::SetFixedSize);

    这可确保窗口小部件的大小仅足以适合sizeHint()的内容。

  4. 考虑到第1点和第2点,“删除国际象棋桌以外的所有内容”的功能可能如下所示:

    void removeButtons() {
        delete addPlaneButton;
        delete cancelButton;
        delete movePlaneButton;
        delete deletePlaneButton;
        delete rotatePlaneButton;
        delete doneButton;
        delete infoLabel;
        delete statusLabel;
    
        formLayout->activate();
        resize(sizeHint());
    }