QScrollArea与QWidget和QVBoxLayout没有像预期的那样工作
问题描述:
所以我有这个QFrame
它是父窗口小部件(在代码中表示为this
)。在这个小部件中,我想在顶部10px处放置一个QWidget
(底部为10px,因此它的高度为140px,而父层为160px)。 QWidget
将在垂直布局中的滚动区域内具有多个自定义按钮,以便当组合的按钮高度超过高度(140px)时,自动滚动设置。由于滚动不是针对整个父窗口小部件的,而仅适用于子窗口小部件,因此滚动应该仅应用于此处的子窗口小部件。这里是我的代码:QScrollArea与QWidget和QVBoxLayout没有像预期的那样工作
//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);
出乎我的意料,这是我得到什么(附图片)。我做错了什么,以及如何解决这个问题?
答
你搞砸了项目的堆栈。具有滚动区域的构思是这样的:
- 在底部是父窗口部件(例如
QDialog
) - 在此之上是在此之上固定大小
- 的滚动区域(
QScrollArea
)在一些大小,这里通常只是其中的一部分是可见的小窗口(QWidget
)(它应该比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();
}
值得一提的约QScrollArea::setWidgetResizable
,其中根据其内容动态调整子控件的大小。
而结果是这样的:
这是有道理的,观察调试信息。 – AlexanderVX 2015-03-03 05:57:54