PDA

View Full Version : QScrollArea not working as expected with QWidget and QVBoxLayout



Cupidvogel
1st March 2015, 17:26
So I have this QFrame which is the parent widget (represented by this in the code). In this widget, I want to place a QWidget at 10 px from top (and 10 px from bottom, as a result of which it will have a height of 140px, whereas parent is 160px). The QWidget will have a number of custom buttons inside it in a vertical layout, in a scroll area, so that when the height of the buttons combined exceeds the QWidget's height (140px), scroll sets in automatically. Because the scroll is not for the entire parent widget, but only for a child widget, the scroll should apply only to the child widget here. Here is my code:



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->setGeometry(x,y,width,160);
this->setStyleSheet("border-radius: 5px; background:red;");

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


Contrary to my expectations, this is what I am getting (attached image). What am I doing wrong, and how do I fix this?

10974

Santosh Reddy
3rd March 2015, 07:19
Do these modifications to your code.

this->setGeometry(x,y,width,160);
this->setStyleSheet("border-radius: 5px; background:red;");

QWidget *dd = new QWidget(this);
//dd->setGeometry(0,10,width,140);//<<<<<<<<<<<<<<<<<<<<<<<<<Remove. Geometry will be managed by layout, don't set it.
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].toStdString(),dd);
layout->addWidget(button);
}

QScrollArea *scroll = new QScrollArea(this);
scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
scroll->setWidget(dd);

QGridLayout * gridLayout = new QGridLayout(this);//<<<<<<<<<<<<<<<<<<<<<<<<<Add
gridLayout->addWidget(scroll);//<<<<<<<<<<<<<<<<<<<<<<<<<Add
gridLayout->setMargin(10);//<<<<<<<<<<<<<<<<<<<<<<<<<Add