1

对于从QWidget继承的自定义小部件,我添加了一个QScrollArea,如下所示:

MainWindow::MainWindow(QWidget *parent) :
    QWidget(parent)//MainWindow is a QWidget
{
    auto *scrollArea = new QScrollArea(this);
    auto *widget = new QWidget(this);

    widget->setStyleSheet("background-color:green");

    scrollArea->setWidget(widget);
    scrollArea->setWidgetResizable(true);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    QVBoxLayout *parentLayout = new QVBoxLayout(widget);

    this->setStyleSheet("background-color:blue");

    for(int i=0;i<12;i++){
        QHBoxLayout* labelLineEdit = f1();
        parentLayout->addStretch(1);
        parentLayout->addLayout(labelLineEdit);
    }

    parentLayout->setContentsMargins(0,0,40,0);
}

QHBoxLayout* MainWindow::f1()
{

    QHBoxLayout *layout = new QHBoxLayout;

    QLabel *label = new QLabel("Movie");
    label->setStyleSheet("background-color:blue;color:white");
    label->setMinimumWidth(300);
    label->setMaximumWidth(300);

    layout->addWidget(label);

    QLineEdit *echoLineEdit = new QLineEdit;
    echoLineEdit->setMaximumWidth(120);
    echoLineEdit->setMaximumHeight(50);
    echoLineEdit->setMinimumHeight(50);

    echoLineEdit->setStyleSheet("background-color:white");

    layout->addWidget(echoLineEdit);

    layout->setSpacing(0);

    return layout;
}

这会产生一个如下所示的窗口:

在此处输入图像描述

问题是,我希望scrollArea占据整个窗口,但事实并非如此。当我调整窗口大小时,它也不会调整大小。

我该如何解决这个问题?

4

1 回答 1

1

问题是,我希望 scrollArea 占据整个窗口,但事实并非如此。当我调整窗口大小时,它也不会调整大小。

原因是您没有设置任何类型的布局来管理QScrollArea小部件本身的定位,因此它只是留给自己的设备(因此它只是为自己选择默认的大小和位置并保持不变大小和位置)。

一个简单的解决方法是将这些行添加到MainWindow构造函数的底部:

QBoxLayout * mainLayout = new QVBoxLayout(this);
mainLayout->setMargin(0);
mainLayout->addWidget(scrollArea);
于 2018-08-16T04:02:59.817 回答