【发布时间】:2019-01-21 11:43:00
【问题描述】:
对于继承自 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 占据整个窗口,但事实并非如此。当我调整窗口大小时,它也不会调整大小。
我该如何解决这个问题?
【问题讨论】:
-
为什么你的 MainWindow 继承自 QWidget 而不是 QMainWindow?
-
在MainWindow的构造函数末尾添加以下内容(
parentLayout->setContentsMargins(0,0,40,0);之后):auto *l = new QVBoxLayout(this); l->addWidget(scrollArea); -
@scopchanov你的问题没有意义,就是MainWindow类一定要继承自QMainWindow,哪里指明了?
-
@eyllanesc,我在问是否有特殊原因不从 QMainWindow 继承。
-
@scopchanov:如果你不介意,你可以看看这个stackoverflow.com/questions/52426751/…的问题!!
标签: c++ qt qscrollarea qlayout qt5.9