【问题标题】:Why is the QScrollArea restricted in size?为什么 QScrollArea 的大小受到限制?
【发布时间】: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-&gt;setContentsMargins(0,0,40,0);之后):auto *l = new QVBoxLayout(this); l-&gt;addWidget(scrollArea);
  • @scopchanov你的问题没有意义,就是MainWindow类一定要继承自QMainWindow,哪里指明了?
  • @eyllanesc,我在问是否有特殊原因不从 QMainWindow 继承。
  • @scopchanov:如果你不介意,你可以看看这个stackoverflow.com/questions/52426751/…的问题!!

标签: c++ qt qscrollarea qlayout qt5.9


【解决方案1】:

问题是,我希望 scrollArea 占据整个 窗口,但它没有。当我调整窗口大小时,它也不会调整大小。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 2017-09-19
    • 1970-01-01
    • 2011-10-02
    • 2018-03-06
    相关资源
    最近更新 更多