QScrollArea with QLayout
Unsolved
General and Desktop
-
Each time when I push the button I would like to add a number to the top of the QVBoyLayout, and each button have to be align to the top, so there is no avaliable space between the buttons, that is why I am using
addStretch()
. When there is no avaliable space inside the layout, then I would like to display the slider, that is why I am usingQScrollArea
. But when I add to much buttons to the layout, the button shrink even though I am usingsetFixedHeight
.So basically I want to keep the button height fixed, and if there is no available space, display the slider.
mainwindow.h:
#pragma once #include <QMainWindow> #include <QFrame> #include <QPushButton> #include <QScrollArea> #include <QVBoxLayout> #include <QResizeEvent> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; QWidget* window; QFrame* frame; QScrollArea* scroll; QVBoxLayout* vlayout; QPushButton* button; int i = 0; void addBtn(); protected: void resizeEvent(QResizeEvent* e); };
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); resize(300,300); window = new QWidget; frame = new QFrame(window); frame->setGeometry(0,0,50,300); scroll = new QScrollArea(window); scroll->setGeometry(50,0,250,300); scroll->setWidgetResizable(true); vlayout = new QVBoxLayout(scroll); vlayout->setMargin(0); vlayout->setSpacing(0); vlayout->addStretch(); button = new QPushButton(window); button->setFixedSize(50,30); button->setText("add"); connect(button, &QPushButton::clicked, this, &MainWindow::addBtn); setMinimumSize(100,100); setCentralWidget(window); } MainWindow::~MainWindow() { delete ui; } void MainWindow::addBtn() { QPushButton* btn = new QPushButton(scroll); btn->setText(QString::number(i)); btn->setFixedHeight(30); ++i; vlayout->insertWidget(0, btn); } void MainWindow::resizeEvent(QResizeEvent *e) { window->resize(e->size()); frame->setGeometry(0,0,50,e->size().height()); scroll->setGeometry(50,0,e->size().width() - 50, e->size().height()); }