2
votes

In a Qt Widget Application, I'm trying to make the following:

Example

My aim is to have a form with a scrollArea with a vertical layout and each item in the scroll area aligned at the top.

Unfortunately, it's only staying in the centre shown here:

Incorrect, should be at the top

I've tried selecting the scrollArea and chaninging vertical alignment from AlignVCenter to AlignTop, but this seems to have no effect.

Alignment

How can I align all the content to the top of the scroll box?

1
Give a try to QtreeView , QTreeWidgetMohammad Kanan
The treeview/widget doesn't allow you to put in buttons or any elements inside itAcidic9
hmm .. how about thisMohammad Kanan
maybe, I tried but it doesn't seem to be what I want, I'm looking more for just a container with a scroll bar (scrollArea) with no columns or rowsAcidic9
This image shows pretty much what I want, it has a scroll box with multiple items (recent projects) and the items start from the topAcidic9

1 Answers

1
votes

You can use a QListWidget to hold a list of not only just text, but also QWidget's (such as push buttons, line edits, etc).

Simply add a QListWidget to your window, and in C++ add the widgets to the QListWidget as needed.

Here are some steps to insert a button into your QListWidget:

Create a QListWidget item into your application.

ss

change selectionMode = NoSelection and focusPolocy = NoFocus

enter image description here

enter image description here

Put the following C++ code into your application:

// Create list item
QListWidgetItem *listWidgetItem = new QListWidgetItem();

// Create widget
QWidget *widget = new QWidget();
QVBoxLayout *verticalLayout = new QVBoxLayout();
verticalLayout->setSizeConstraint(QLayout::SetFixedSize);
widget->setLayout(verticalLayout);

// Add button to widget layout
QPushButton *pushButton = new QPushButton("Button!");
verticalLayout->addWidget(pushButton);

// Add list item to ul->listWidget
listWidgetItem->setSizeHint(widget->sizeHint()); // Set the size of the list item to the same as the widget
ui->listWidget->addItem(listWidgetItem);
ui->listWidget->setItemWidget(listWidgetItem, widget);

Old answer:

I found my answer here but I will re-post it for anyone else interested.

To align elements at the top of a scroll area, add a vertical layout as a child to the scroll area and put all your elements inside that vertical layout. Like so:

Screenshot

In your C++, add a spacer item to your vertical layout inside the scroll area by using addStretch():

ui->verticalLayout->addStretch();

All the items should now magically be aligned to the top.

Edit:

This seems to only work for the very first item, and all other items are not pushed up to the top.