当前位置: 代码迷 >> 综合 >> QScrollArea 动态加载控件
  详细解决方案

QScrollArea 动态加载控件

热度:74   发布时间:2023-10-14 22:02:35.0

文章目录

    • 说明
    • 代码

说明


文章转载自:QScrollArea里动态添加控件,并自动滚动到最底部

代码


/** 注:动态构建的 TabWidget 包含关系如下:* 1. 首先创建一个 TabWidget* 2. 创建若干 Tab 页* 3. 每个页面新建一个 QScrollArea* 4. 每个 QScrollArea host 一个 QWidget* 5. 每个 QWidget 放置一个 QVBoxLayout* 6. 每个 QVBoxLayout 防止具体的自定义控件*/void init() {
     //初始化m_pScrollAreaContentWidget = new QWidget(this);m_pScrollAreaContentWidget->setObjectName("m_pScrollAreaContentWidget");m_pContentWidgetLayout = new QVBoxLayout;m_pContentWidgetLayout->setSpacing(16 * m_dScaleFactor);m_pContentWidgetLayout->setMargin(0);m_pContentWidgetLayout->setContentsMargins(0, 0, 0, 0);m_pContentWidgetLayout->setAlignment(Qt::AlignTop);m_pScrollAreaContentWidget->setFixedWidth(this->width() - 17 * m_dScaleFactor);m_pScrollAreaContentWidget->setLayout(m_pContentWidgetLayout);m_pScrollArea = new QScrollArea(this);//加10是为了留出滚动条的位置,以防向左抖动//滚动条据边框距离为7m_pScrollArea->setFixedWidth(m_pScrollAreaContentWidget->width() + 10 * m_dScaleFactor);m_pScrollArea->setObjectName("m_scrollArea");m_pScrollArea->setWidgetResizable(true);m_pScrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);m_pScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);m_pScrollArea->setStyleSheet("QAbstractScrollArea#m_scrollArea{border: none;}");QScrollBar *scrBar = m_pScrollArea->verticalScrollBar();scrBar->setFixedWidth(10 * m_dScaleFactor);scrBar->setStyleSheet(QString("QScrollBar:vertical{""width:%5px;background-color:#F2F3F9;""margin:0px,0px,0px,0px;""padding-top:0px;padding-bottom:0px;padding-right:%1px;}""QScrollBar::handle:vertical{""border-radius: %2px;width:%3px;""background: rgb(0, 0, 0, 20);min-height:%4px;}""QScrollBar::handle:vertical:hover{""border-radius: %2px;width:%3px;""background:rgb(0, 0, 0, 30);min-height:%4px;}""QScrollBar::handle:vertical:pressed{""border-radius: %2px;width:%3px;""background:rgb(0, 0, 0, 40);min-height:%4px;}""QScrollBar::sub-line:vertical, QScrollBar::add-line:vertical""{width: 0px;height: 0px; background:#ffffff}""QScrollBar::add-page:vertical,QScrollBar::sub-page:vertical""{background: #ffffff;}").arg(0 * m_dScaleFactor).arg(int(4 * m_dScaleFactor)).arg(10 * m_dScaleFactor).arg(int(20 * m_dScaleFactor)).arg(int(10 * m_dScaleFactor)));m_pScrollArea->setWidget(m_pScrollAreaContentWidget);m_pScrollArea->setContentsMargins(0, 0, 0, 0);m_pScrollArea->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
}void slotAddWidget() {
     //插入控件,并滚动HHContectWidget *wid = new HHContectWidget(this);m_pContentWidgetLayout->addWidget(wid);m_pScrollArea->ensureWidgetVisible(wid);m_pScrollAreaContentWidget->setFixedHeight(m_vPronunciationEdit.count() * 48 * m_dScaleFactor); //m_pScrollArea->verticalScrollBar()->setValue(m_vPronunciationEdit.count() * 48 * m_dScaleFactor); /
}