【问题标题】:Custom widgets in scroll area not respecting minimum?滚动区域中的自定义小部件不尊重最小值?
【发布时间】:2018-01-30 18:02:22
【问题描述】:

我越来越接近让 QScrollArea 工作,但它仍在缩小我的自定义小部件,因为它们被添加。一切都在流畅地调整大小,如果滚动区域太小,则会出现滚动条,因此它显然有一些最小尺寸的概念。

一开始,滚动区域中有两个自定义小部件,您可以看到一些缩小:

这是临界点下方的同一个窗口。文本现在完全消失了,但它不会缩小 QLineEdit,所以它最后添加了一个滚动条。 (滚动区域为蓝色背景,内容小部件为紫色)

我从设计开始,但滚动区域小部件下方的所有内容都在代码中,因为我无法使用设计使垂直布局正常工作。

这是起点:

StackWidget 中有一个页面,它在垂直布局中有两个元素。滚动区域有一个 QWidget。 MainWindow 的构造函数定义了一个垂直布局,将其分配给成员scrollWidgetLayout,并将该布局提供给滚动区域的小部件:

scrollWidgetLayout = new QVBoxLayout(ui->scrollAreaWidgetContents);
ui->scrollAreaWidgetContents->setLayout(scrollWidgetLayout);

应用程序从堆栈小部件的第一页开始,用户登录,然后应用程序运行以从服务器获取记录。每条记录都变成一个小部件:

RecordFolderWidget::RecordFolderWidget(Record *r, QWidget *parent) : QWidget(parent)
{
    record = r;
    //setSizePolicy(QSizePolicy::Expanding, QSizePolicy::MinimumExpanding);

    QGridLayout *layout = new QGridLayout();
    pathLineEdit = new QLineEdit();
    finderButton = new QPushButton("...");
    QLabel *nameLabel = new QLabel(record->name);
    layout->setSpacing(5);
    layout->setMargin(3);
    layout->addWidget(nameLabel, 0, 0, 0, 1, Qt::AlignCenter);
    layout->addWidget(pathLineEdit, 1, 0);
    layout->addWidget(finderButton, 1, 1);
    setLayout(layout);
    //setMinimumHeight(sizeHint().height());
}

请注意,有一些行被注释掉了,这些是我一直在尝试让它工作的东西。顺便说一句,sizeHint 似乎是正确的,并且没有改变。

一旦创建了这个小部件,它就会被添加到滚动区域的小部件中:

    RecordFolderWidget *rf = new RecordFolderWidget(record);
    rf->setParent(ui->scrollAreaWidgetContents);

    scrollWidgetLayout->addWidget(rf);

我也尝试在这里调整滚动区域内容的大小,但没有成功:

ui->scrollAreaWidgetContents->resize(rfSize.width(), rfSize.height() * records.count());

其中 rfSize 在创建后从自定义小部件的 sizeHint 中提取出来,并且在循环之后调用了该行一次以创建/添加所有小部件。

除了上面的 setMinimumHeight 和 resize 之外,我尝试将 scrollAreaWidgetContents 的 SizePolicy 从首选更改为展开到最小展开,但没有发现任何差异。我确定我错过了一些微不足道的东西,但就是找不到。

【问题讨论】:

  • pfscrollWidgetLayout是什么?
  • pf 是我在将原始代码复制到示例代码时错过了重命名的地方,而 scrollWidgetLayout 是在构造函数中初始化的 QVBoxLayout 成员,如设计屏幕截图下方所述。

标签: c++ qt5 qwidget qscrollarea qlayout


【解决方案1】:

我在您的代码中看到的问题是,在添加 QLabel 时,您将 rowSpan 设置为 0,我已对其进行了更改,并且可以正确观察到它。在下一部分中,我将展示我的测试代码和结果:

QVBoxLayout *scrollWidgetLayout = new QVBoxLayout(ui->scrollAreaWidgetContents);

for(int i=0; i<10; i++){
    QWidget *widget = new QWidget;
    QGridLayout *layout = new QGridLayout(widget);
    QLineEdit *pathLineEdit = new QLineEdit;
    QPushButton *finderButton = new QPushButton("...");
    QLabel *nameLabel = new QLabel(QString("name %1").arg(i));
    layout->setSpacing(5);
    layout->setMargin(3);
    layout->addWidget(nameLabel, 0, 0, 1, 1, Qt::AlignCenter);
    layout->addWidget(pathLineEdit, 1, 0);
    layout->addWidget(finderButton, 1, 1);

    scrollWidgetLayout->addWidget(widget);
}

【讨论】:

  • 天哪,大眼睛。我将跨度误读为额外的行/列,而不是总数。鉴于此,我希望 colspan 为 2。谢谢!
猜你喜欢
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 2017-10-14
  • 2019-08-13
  • 2018-09-17
相关资源
最近更新 更多