如何使用 QHBoxLayout 和 QScrollArea 创建一个可滚动的小部件

How to create a scrollable widget using QHBoxLayout and QScrollArea

我正在尝试使用 QHBoxLayout 和 QScrollArea 创建一个可滚动的小部件,但我无法成功创建一个 GUI,这是我的代码,任何人都可以告诉我我需要更改的地方。 任何帮助将不胜感激

mainLayout = new QHBoxLayout(this);
mainLayout->setSizeConstraint(QLayout::SetMaximumSize);
QCheckBox *sam_box = new QCheckBox(this);
sam_box->setText("HAIIIIIIIIIII");
sam_box->setFixedSize(10000,10000);
QCheckBox *so_box = new QCheckBox(this);
so_box->setText("HOWWWWWWWWWWWW");
so_box->setFixedSize(150000,15000);
mainLayout->addWidget(sam_box);
mainLayout->addWidget(so_box);

QScrollArea *scrollarea = new QScrollArea(this);
scrollarea->setBackgroundRole(QPalette::Shadow);
scrollarea->setFixedSize(700,500);
scrollarea->setLayout(mainLayout);`

Here is my output screen

提前致谢, Rohith.G

实现此目的的一种方法是通过以下逻辑 centralwidget() -> QHBoxLayout-> QScrollArea -> QWidget-> 添加复选框

代码流程和注释将详细解释逻辑。

QWidget *wgt = new QWidget();//new code
    wgt->setGeometry(0,0,500,500); //new code
    //QHBoxLayout mainLayout = new QHBoxLayout(this);
    QHBoxLayout *mainLayout = new QHBoxLayout(this->centralWidget());

    mainLayout->setSizeConstraint(QLayout::SetMaximumSize);
    //QCheckBox *sam_box = new QCheckBox(this);
    QCheckBox *sam_box = new QCheckBox(wgt);
    sam_box->setText("HAIIIIIIIIIII");

    //sam_box->setFixedSize(10000,10000);
    sam_box->setFixedSize(200,200); //make it small for quick testing

    //QCheckBox *so_box = new QCheckBox(this);
    QCheckBox *so_box = new QCheckBox(wgt);
    so_box->setText("HOWWWWWWWWWWWW");

    //so_box->setFixedSize(150000,15000);
    so_box->setFixedSize(150,150); //make it small for quick testing

    //mainLayout->addWidget(sam_box);
    //mainLayout->addWidget(so_box);

    QScrollArea *scrollarea = new QScrollArea();
    scrollarea->setBackgroundRole(QPalette::Shadow);
    //scrollarea->setFixedSize(700,500); //scroll area cant be resized
    mainLayout->addWidget(scrollarea); //new code
    //scrollarea->setLayout(mainLayout);
    scrollarea->setWidget(wgt);

下面的代码将生成 30 个 QCheckBoxes,每 10 个添加到垂直框布局中,所有垂直布局都添加到水平框布局中

QScrollArea *scrl = new QScrollArea();
    scrl->setGeometry(0,0,300,300);
    QWidget *wgtMain = new QWidget();
    QHBoxLayout *hboxMain = new QHBoxLayout(wgtMain);
    for(int iCount=0;iCount<3;iCount++){
        QWidget *wgtSub = new QWidget();
        QVBoxLayout *vboxSub = new QVBoxLayout(wgtSub);
        for(int jCount=0;jCount<10;jCount++){
            QCheckBox *chk = new QCheckBox("Check Box " + QString::number(jCount+1) + " of " + QString::number(iCount+1));
            vboxSub->addWidget(chk);
        }
        hboxMain->addWidget(wgtSub);
    }
    scrl->setWidget(wgtMain);
    scrl->show();