Search code examples
pythonqtpyqtqgraphicsview

QGraphicsView with automatic items placing


I would like to write an asset browser using QGraphicsView. It's a little different from examples using QGraphicsView and QGraphicsItems, because I want only one scrollbar and I want items to move automatically, when the viewport size changes. For example, when viewport width is large enough to display 4 asssets, they should be displayed like this:

aaaa
aaaa
aa

but when viewport is shrinked and can only contain 3 in a row, it should display them like this:

aaa
aaa
aaa
a

I wouldn't like to have to move those asset's by myself and let the graphics view manage them all. Is it somehow possible?

I have written once such a thing, but using QWidget and paintEvent, drawing all assets myself and keeping track of how many assets can be displayed in a row. Can it be done simpler with QGraphicsView?


Solution

  • QGraphicsView supports layouts. What you have to do is implement your own layout manager, inheriting from QGraphicsLayout.

    For the layout you require, take a look at the Flow Layout example of Qt. Converting that example will give you a QGraphicsFlowLayout. Add your QGraphicsItems to this layout and set your QGraphicsView's layout to that layout, and that would do the trick.