标签归档:Fill area

QVBoxLayout: 如何填充剩下的区域

大部分情况我们希望一个Layout中会放一些QWidget,其中一个QWidget填充剩下的区域,比如下面的代码,要求在一个Layout的顶端放置一个Title Bar、底端放置一个Status Bar、中间放一个填满剩余区域的QWidget:

AliceNetworkMonitor 构造函数:


AliceNetworkMonitor::AliceNetworkMonitor(QWidget* parent)
    : QMainWindow(parent)
{
    // 设置主布局
    m_mainLayout = new(std::nothrow) QVBoxLayout();
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(0);

    // 设置UI
    ui.setupUi(this);
    // Set mainLayout as the root layout
    ui.centralWidget->setObjectName("widget_main_window");
    ui.centralWidget->setLayout(m_mainLayout);

    // 设置windows图标
  setWindowIcon(QIcon(":/AliceNetworkMonitor/Resources/windowicon_alice.png"));  

    // 初始化菜单栏
    initTitleBar();

    // 初始化中间栏
    QHBoxLayout* centerLayout = new(std::nothrow) QHBoxLayout();
    centerLayout->setContentsMargins(0, 0, 0, 0);
    centerLayout->setSpacing(0);
    m_centerWidget = new(std::nothrow)QWidget();
    m_centerWidget->setObjectName("cld_border_widget");
    m_centerWidget->setLayout(centerLayout);

    // 初始化状态栏
    initStatusBar();

    // 添加到mainLayout
    m_mainLayout->addWidget(m_titleBar, 0, Qt::AlignTop);
    m_mainLayout->addWidget(m_centerWidget);
    m_mainLayout->addWidget(m_statusWidget, 0, Qt::AlignBottom);


    retranslateUi();
}

结果会是这个样子的:

预期的 m_centerWidge 并没有填充整个剩下的区域。

改进办法很简单, m_centerWidge 使用QSizePolicy::Expanding就行了:


    m_centerWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

完整代码如下:

AliceNetworkMonitor::AliceNetworkMonitor(QWidget* parent)
    : QMainWindow(parent)
{
    // 设置主布局
    m_mainLayout = new(std::nothrow) QVBoxLayout();
    m_mainLayout->setContentsMargins(0, 0, 0, 0);
    m_mainLayout->setSpacing(0);

    // 设置UI
    ui.setupUi(this);
    // Set mainLayout as the root layout
    ui.centralWidget->setObjectName("widget_main_window");
    ui.centralWidget->setLayout(m_mainLayout);

    // 设置windows图标
  setWindowIcon(QIcon(":/AliceNetworkMonitor/Resources/windowicon_alice.png"));  

    // 初始化菜单栏
    initTitleBar();

    // 初始化中间栏
    QHBoxLayout* centerLayout = new(std::nothrow) QHBoxLayout();
    centerLayout->setContentsMargins(0, 0, 0, 0);
    centerLayout->setSpacing(0);
    m_centerWidget = new(std::nothrow)QWidget();
    m_centerWidget->setObjectName("cld_border_widget");
    m_centerWidget->setLayout(centerLayout);
    m_centerWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 初始化状态栏
    initStatusBar();

    // 添加到mainLayout
    m_mainLayout->addWidget(m_titleBar, 0, Qt::AlignTop);
    m_mainLayout->addWidget(m_centerWidget);
    m_mainLayout->addWidget(m_statusWidget, 0, Qt::AlignBottom);


    retranslateUi();
}

结果如下: