在滚动区使用自定义Qt类,并强制不调整元素的大小,但滚动条出现

Using custom Qt class in Scroll Area and forcing not to resize elements but scroll bar to appear

本文关键字:元素 调整 滚动条 滚动区 自定义 Qt      更新时间:2023-10-16

我试着解决这个问题好几天了,但我没有进展,我想我错过了什么,请帮助我解决它。

在主窗口中,我创建了滚动区,并给它垂直布局。我已经创建了Qt设计师类(myform.h, myform.cpp和myform.ui),并把一些按钮+垂直布局。

这是"myform"。用户界面:http://oi59.tinypic.com/23sch2r.jpg

我想在主窗口的滚动区域包含"myform"。Ui",以及"myform"中的元素。Ui "将不会调整大小,但滚动条出现在滚动区域。

My mainwindow.cpp is

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "myform.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    MyForm* myform = new MyForm(this);
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(myform);
    ui->scrollArea->setWidgetResizable(false);
    ui->scrollArea->setLayout(layout);
}
MainWindow::~MainWindow()
{
    delete ui;
}

问题是滚动条没有出现,并且元素在调整窗口大小时正在调整大小。

图片:http://oi62.tinypic.com/w83xvp.jpg

这只是一个最小的例子来说明我所遇到的问题。

根据QScrollArea的文档,看起来您必须将背景小部件设置为滚动区域。这段代码直接取自QScrollArea小部件的文档:

QLabel *imageLabel = new QLabel;
QImage image("happyguy.png");
imageLabel->setPixmap(QPixmap::fromImage(image));
scrollArea = new QScrollArea;
scrollArea->setBackgroundRole(QPalette::Dark);
scrollArea->setWidget(imageLabel);
创建一个图像标签。将一个像素图加载到其中。然后,滚动区域小部件由setWidget()命令指定。

在你的代码中,我认为ui->scrollArea->setLayout(layout);

应为

ui->scrollArea->setWidget(layout);代替

注:我没有测试过这段代码,但认为它会解决你的问题。