实现效果:
(1)首先要理解 QScrollArea控件出现滚动条的方式,具体参考(11条消息) QT的自动滚动区QScrollArea的用法,图文详解_暴躁的野生猿的博客-CSDN博客_qscrollarea
在scrollArea的子控件设置mininumSize就是显示滚动条关键;
(2)在 QScrollArea 添加自定义控件(这里以添加QPushButton)为例子;具体代码:
int leftRightMargin = 40;
int btnWidth = ui->scrollArea->width()-leftRightMargin;
int btnHeight = 20;
int elemSpaceing = 4;
int btnNum = 30;
for(int i=0; i<btnNum; i++){
QPushButton * btn = new QPushButton("btn ************* abcd",ui->scrollAreaWidgetContents);
btn->setGeometry(leftRightMargin/2, elemSpaceing*(i+1)+i*btnHeight, btnWidth, btnHeight);
btn->show();
btnGroup->addButton(btn);
}
int contextHeight = btnNum*btnHeight + (btnNum+1)*elemSpaceing;
ui->scrollAreaWidgetContents->setMinimumHeight(contextHeight); // 将添加控件内容总高度设置MininumHeight 是出现滚动条的关键
注意: 修改一定要采用 ui->scrollArea->width(),不然在多次加载会导致计算出问题
如果采用这个计算ui->scrollAreaWidgetContents->width(),在多次加载后,大小会变,导致计算偏移,情况如图:
第三步,在resizeEvent中,对自定义控件宽高进行调整,实现布局效果;文章来源:https://www.toymoban.com/news/detail-501807.html
void MainWindow::resizeEvent(QResizeEvent *event)
{
int leftRightMargin = 40;
// 修改一定要采用 ui->scrollArea->width(),不然在多次加载会导致计算出问题
// 如果采用这个计算ui->scrollAreaWidgetContents->width(),在多次加载后,大小会变,
// 导致计算偏移
int btnWidth = ui->scrollArea->width()-leftRightMargin;
int btnHeight = 20;
int elemSpaceing = 4;
int i=0;
for(QAbstractButton * btn : btnGroup->buttons()){
btn->setGeometry(leftRightMargin/2, elemSpaceing*(i+1)+i*btnHeight, btnWidth, btnHeight);
i++;
}
QMainWindow::resizeEvent(event);
}
完整代码:文章来源地址https://www.toymoban.com/news/detail-501807.html
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QResizeEvent>
#include <QPushButton>
#include <QTimer>
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
btnGroup = new QButtonGroup(this);
// 延迟加载,不然得到ui->scrollAreaWidgetContents->width()会异常
QTimer::singleShot(500, this, [this]()
{
int leftRightMargin = 40;
int btnWidth = ui->scrollArea->width()-leftRightMargin;
int btnHeight = 20;
int elemSpaceing = 4;
int btnNum = 30;
for(int i=0; i<btnNum; i++){
QPushButton * btn = new QPushButton("btn ************* abcd",ui->scrollAreaWidgetContents);
btn->setGeometry(leftRightMargin/2, elemSpaceing*(i+1)+i*btnHeight, btnWidth, btnHeight);
btn->show();
btnGroup->addButton(btn);
}
int contextHeight = btnNum*btnHeight + (btnNum+1)*elemSpaceing;
ui->scrollAreaWidgetContents->setMinimumHeight(contextHeight);
});
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::resizeEvent(QResizeEvent *event)
{
int leftRightMargin = 40;
int btnWidth = ui->scrollArea->width()-leftRightMargin;
int btnHeight = 20;
int elemSpaceing = 4;
int i=0;
for(QAbstractButton * btn : btnGroup->buttons()){
btn->setGeometry(leftRightMargin/2, elemSpaceing*(i+1)+i*btnHeight, btnWidth, btnHeight);
i++;
}
QMainWindow::resizeEvent(event);
}
到了这里,关于Qt QScrollArea显示控件,并且调节控件大小的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!