QScrollArea与QWidget和QVBoxLayout无法正常工作

Sex*_*ast 5 c++ qt qwidget qscrollarea qframe

所以我有这个QFrame是父窗口小部件(this在代码中表示).在这个小部件中,我想QWidget从顶部放置一个10 px(从底部放置10 px,因此它的高度为140px,而父级为160px).在QWidget将具有多个在其内部自定义按钮在垂直布局,在滚动区域,使得当按钮组合的高度超过QWidget's在自动高度(140px),滚动集.由于滚动不是针对整个父窗口小部件,而是针对子窗口小部件,因此滚动应仅适用于此处的子窗口小部件.这是我的代码:

//this is a custom button class with predefined height and some formatting styles
class MyButton: public QPushButton
{

public:
    MyButton(std::string aText, QWidget *aParent);

};

MyButton::MyButton(std::string aText, QWidget *aParent): QPushButton(QString::fromStdString(aText), aParent)
{
    this->setFixedHeight(30);
    this->setCursor(Qt::PointingHandCursor);
    this->setCheckable(false);
    this->setStyleSheet("background: rgb(74,89,98);   color: black; border-radius: 0px; text-align: left; padding-left: 5px; border-bottom: 1px solid black;");
}

//this is where I position the parent widget first, and then add sub widget
this->setGeometry(x,y,width,160);
this->setStyleSheet("border-radius: 5px; background:red;");

//this is the widget which is supposed to be scrollable
QWidget *dd = new QWidget(this);
dd->setGeometry(0,10,width,140);
dd->setStyleSheet("background: blue;");

QVBoxLayout *layout = new QVBoxLayout();
dd->setLayout(layout);

for (int i = 0; i < fValues.size(); i++)
{
    MyButton *button = new MyButton(fValues[i],dd);
    layout->addWidget(button);
}

QScrollArea *scroll = new QScrollArea(this);
scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
scroll->setWidget(dd);
Run Code Online (Sandbox Code Playgroud)

与我的期望相反,这就是我得到的(附图).我做错了什么,我该如何解决这个问题?

在此输入图像描述

Bog*_*dan 10

你弄乱了一堆物品.具有可滚动区域的想法是这样的:

  • 底部是父窗口小部件(例如QDialog)
  • 除此之外是可QScrollArea固定大小的可滚动区域()
  • 除此之外是一个QWidget大小的widget(),通常只有部分可见(它应该比scrollarea大)
  • 除此之外是一个布局
  • 和最后:布局管理子项目(QPushButton这里的几个)

试试这段代码:

int
main( int _argc, char** _argv )
{
    QApplication app( _argc, _argv );

    QDialog * dlg = new QDialog();
    dlg->setGeometry( 100, 100, 260, 260);

    QScrollArea *scrollArea = new QScrollArea( dlg );
    scrollArea->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOn );
    scrollArea->setWidgetResizable( true );
    scrollArea->setGeometry( 10, 10, 200, 200 );

    QWidget *widget = new QWidget();
    scrollArea->setWidget( widget );

    QVBoxLayout *layout = new QVBoxLayout();
    widget->setLayout( layout );

    for (int i = 0; i < 10; i++)
    {
        QPushButton *button = new QPushButton( QString( "%1" ).arg( i ) );
        layout->addWidget( button );
    }

    dlg->show();

    return app.exec();
}
Run Code Online (Sandbox Code Playgroud)

值得一提的是QScrollArea::setWidgetResizable,它根据内容动态调整子窗口小部件的大小.

结果如下:

在此输入图像描述

  • 感谢`scrollArea-&gt;setWidgetResizable(true);`。没有它,包含的布局似乎无法正确布局。 (3认同)