Search code examples
c++qtqt5qlistviewqstyleditemdelegate

Qt5 QListView set up items in a horizontal row instead of vertical list


I am setting up a QListView with a custom QStyledItemDelegate and I would like to have my items rendered so they are in a horizontal 'row'.

Assuming our QListView has models that are "A", "B", and "C", the standard view will have them as:

----------------------------------------------------------------------------------
|X[ A                                                                          ]X|
| [ B                                                                          ] |
| [ C                                                                          ] |
----------------------------------------------------------------------------------

with each item taking up the entire width. What I want to do is have A B and C in a horizontal orientation even though the model has each one in a separate row (and only one column throughout the view).

X[ A ]X [ B ] [ C ]

(X == selected item background)

The reason I cannot use a QTableView is because I will have the items increase and decrease in size, therefore require wrapping when they get too wide to fit on one line; constantly changing the columns, rows, and cell sizes in a table seems like more work than is necessary for this to work, plus I don't want table borders in the view.

So far I've tried overriding sizeHint and paint methods. I don't think I need editor methods because these items won't have an edit mode to go into.

Any basic example would be sufficient for me. If you write your answer in PyQt5 and it helps me to find my answer, I'll mark it as the correct answer even though I'm using C++.


Solution

  • You can change the flow property from "TopToBottom" to "LeftToRight" with setFlow as below:

    listView->setFlow(QListView::Flow::LeftToRight);