I am currently working on a Qt project for my school. For this project I need to list an unknown number of elements in a window without resizing its content.
I've used some VBoxLayout
in the past, but it isn't what I am searching at all. This widget re开发者_如何学运维sizes its content depending on the number of elements it contains. What I would like is to add as much widgets as I need into the "scrolling widget", which will stack next to each other automatically and won't resize.
I tried using QScrollArea
but I wasn't able to make elements stack on each others.
Here is a small drawing explaining my problem:
Here is how I do it with a QVBoxLayout
and a QScrollArea
:
//scrollview so all items fit in window
QScrollArea* techScroll = new QScrollArea(tabWidget);
techScroll->setBackgroundRole(QPalette::Window);
techScroll->setFrameShadow(QFrame::Plain);
techScroll->setFrameShape(QFrame::NoFrame);
techScroll->setWidgetResizable(true);
//vertical box that contains all the checkboxes for the filters
QWidget* techArea = new QWidget(tabWidget);
techArea->setObjectName("techarea");
techArea->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
techArea->setLayout(new QVBoxLayout(techArea));
techScroll->setWidget(techArea);
Then when adding items you do it like this (with lay = techArea->layout()
and parent = techarea
:
for(std::set<Event::Enum>::iterator it = validEvents.begin(); it != validEvents.end();
++it){
QCheckBox* chk = new QCheckBox(
"text", parent);
if(lay){
lay->addWidget(chk);
}
}
If your display elements are simple, the easiest solution is a QListWidget
. This will automatically resize itself and inform the QScrollArea
when you add items. You just have to call myScrollAlrea -> setWidget (myListWidget)
to initialise, and then myListWidget -> addItem (myListWidgetItem)
to add new items.
RedX's answer was a bit vague, but I got his method to work:
QRadioButton *radio[40];
for (int i = 0;i<40;i++)
radio[i] = new QRadioButton(tr("&Radio button 1"));
QWidget* techArea = new QWidget;
techArea->setObjectName("techarea");
techArea->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
techArea->setLayout(new QVBoxLayout(techArea));
ui->scrollArea->setWidget(techArea);
QLayout *lay = techArea->layout();
for (int i = 0;i<40;i++)
lay->addWidget(radio[i]);
精彩评论