2

我想在 QGroupBox 中有一个 QScrollArea,所以当我将新的小部件添加到组框时,它的大小保持不变,但我有滚动条而不是调整组框本身的大小。

这是我的代码:

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QtCore>
#include <QtGui>
#include <QLayout>
#include <QScrollArea>
#include <QGroupBox>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QGroupBox *box = new QGroupBox(QObject::tr("Example"));
    QScrollArea *sa = new QScrollArea;

    QGridLayout *gridLayout = new QGridLayout;
    QPushButton *b1 = new QPushButton("A");
    QPushButton *b2 = new QPushButton("B");
    QPushButton *b3 = new QPushButton("C");
    QPushButton *b4 = new QPushButton("D");
    QPushButton *b5 = new QPushButton("E");
    QPushButton *b6 = new QPushButton("F");
    QPushButton *b7 = new QPushButton("F");
    QPushButton *b8 = new QPushButton("F");
    QPushButton *b9 = new QPushButton("F");

    // addWidget(*Widget, row, column, rowspan, colspan)
    // 0th row
    gridLayout->addWidget(b1,0,0,1,1);
    gridLayout->addWidget(b2,0,1,1,1);
    gridLayout->addWidget(b3,0,2,1,1);

    // 1st row
    gridLayout->addWidget(b4,1,0,1,1);

    // 2nd row with 2-column span
    gridLayout->addWidget(b5,2,0,1,2);

    // 3rd row with 3-column span
    gridLayout->addWidget(b6,3,0,1,3);

    gridLayout->addWidget(b7,4,0,1,3);

    gridLayout->addWidget(b8,5,0,1,3);

    gridLayout->addWidget(b9,6,0,1,3);

    box->setLayout(gridLayout);
    sa->setWidget(box);

    setCentralWidget(sa);
}

MainWindow::~MainWindow()
{
    delete ui;
}

我现在拥有的是,每次我添加一个新的 QPushButton 时,QGroupBox 都会调整大小,不管有没有 QScrollArea。我应该改变什么以获得我想要的行为?可能吗?

4

1 回答 1

2

那是因为您将 groupbox 放在滚动区域内。滚动区域不限制其子项的大小。

您应该做相反的事情,将滚动区域放在组框内。方法如下;

QWidget* sw = new QWidget();
sw->setLayout(gridLayout);
sa->setWidget(cont);
QVBoxLayout* bl = new QVBoxLayout(box);
bl->addWidget(sa);

setCentralWidget(box);

请注意,如果您使用切换按钮(例如单选按钮),它们将不会作为一个组。因为从技术上讲,它们不再在同一个 QGroupBox 中——它们在滚动区域内。您可以使用QButtonGroup实例提供组行为。

于 2015-11-15T13:25:16.253 回答