在隐藏子项时调整qt小部件的大小

lau*_*ura 15 qt resize qwidget

当重试子项被隐藏时,我将如何调整窗口小部件的大小,使其看起来像在第一个图像中?主要布局是QVBoxLayout,重试子是一个带有QVBoxLayout的小部件.

我尝试过以下方法:

  • 更新()
  • updateGeometry()
  • setGeometry(childrenRect())
  • 布局() - >激活()

一旦我将重试小部件设置为隐藏,就在主小部件上.我是否需要拦截某些事件才能执行此操作?

Pat*_*ola 18

adjustSize功能可以做你想要的.

  • 对我有用的是将我的主布局的sizeConstraint设置为QLayout :: SetFixedSize.换句话说,mainLayout-> setSizeConstraint(QLayout :: SetFixedSize); (2认同)

小智 6

这是一个基本的例子,可以在小部件隐藏/显示时自动调整大小.

dialog.h文件:

#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QtGui>

class dialog : public QDialog
{
    Q_OBJECT


public:
    explicit dialog(QWidget *parent = 0)
    {

        vlayout.addWidget(&checkbox);
        vlayout.addWidget(&label);
        label.setText("Label");

        setLayout(&vlayout);
        this->layout()->setSizeConstraint(QLayout::SetFixedSize); // !!! This is the what makes it auto-resize

        checkbox.setChecked(true);
        connect(&checkbox,SIGNAL(toggled(bool)),&label,SLOT(setVisible(bool)));
    }

private:
    QVBoxLayout vlayout;
    QCheckBox checkbox;
    QLabel label;

};

#endif // DIALOG_H
Run Code Online (Sandbox Code Playgroud)

和main.c

#include <QApplication>
#include "dialog.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    dialog d;
    d.show();
    return a.exec();
}
Run Code Online (Sandbox Code Playgroud)