QStBox中的QScrollArea,滚动条而不是调整QGroupBox的大小

我想在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 . 我应该改变什么才能拥有我想要的行为?可能吗?

回答(1)

3 years ago

那是因为你将组合框放在滚动区域内 . 滚动区域不限制其儿童的大小 .

你应该做相反的事情,把scrollarea放在组合框中 . 这是怎么回事;

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

setCentralWidget(box);

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