1
votes

To my custom widget, inherited from QWidget, I have added a QScrollArea like this:

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;
}

This produces a window which looks like this:

enter image description here

The problem is, that I want the scrollArea to occupy the entire window, but it does not. It also doesn't get resized when I resize the window.

How could I fix this?

1
Why your MainWindow is inheriting from QWidget and not from QMainWindow?scopchanov
add the following at the end of the constructor of MainWindow (after parentLayout->setContentsMargins(0,0,40,0);): auto *l = new QVBoxLayout(this); l->addWidget(scrollArea);scopchanov
@scopchanov Your question does not make sense, that is, the MainWindow class must necessarily inherit from QMainWindow, where is it indicated?eyllanesc
@eyllanesc, I am asking if there is a special reason not to inherit from QMainWindow.scopchanov
@scopchanov:If you dont mind,could you have a look at this stackoverflow.com/questions/52426751/… question!!adi

1 Answers

1
votes

The problem is, that I want the scrollArea to occupy the entire window, but it does not. It also doesn't get resized when I resize the window.

The reason is that you have not set any kind of layout to manage the positioning of your QScrollArea widget itself, so it is just being left to its own devices (and therefore it just chooses a default size-and-location for itself and stays at that size-and-location).

A simple fix would be to add these lines to the bottom of your MainWindow constructor:

QBoxLayout * mainLayout = new QVBoxLayout(this);
mainLayout->setMargin(0);
mainLayout->addWidget(scrollArea);