本文主要是介绍Qt QScrollArea显示控件,并且调节控件大小,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
实现效果:
(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中,对自定义控件宽高进行调整,实现布局效果;
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);
}
完整代码:
#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显示控件,并且调节控件大小的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!