I am trying to make a grid on a QGraphicsView and QGraphicsScene with custom QGraphicsWidgets, but I am not sure how the best way to do this would be. I'm working with PyQt4, but this is a general Qt question.
My current implementation contains the following. One QGraphicsScene (with view) and one QGraphicsWidget that contains the QGraphicsGridLayout onto which I insert my custom widgets.
The problem I'm having is that each of these custom widgets has different sizes, and they overlap and I'm not sure as to how I would go about changing the sizes for each widget separately. Also, the grid needs to be "responsive" i.e. if the widget is some width, then there should be 3 columns, but if the widget is smaller, only 2 columns should be displayed.
I've read this may be solvable by implementing the size hints, but I haven't really found any good documentation on that topic.
So my questions are:
- Is there a better way to make the hierarchy of widgets, my current one seems excessive (Scene > Widget > Layout > Widgets)
When I use the QGraphics....
classes, I generally will subclass QGraphicsView
. The view will create it's own scene and have convenience methods for creating all the child items as well. From an api standpoint, only the view widget is really exposed.
- What's the best way to make different sized widgets the same size (so they would all appear the same size in the grid and not overlap)?
It depends what types of widgets they are. If they are images/pixmaps, you can just scale them to a certain size. If they are actual widgets with controls, you probably don't want to scale them and should just set their actual height/width using setGeometry
. Otherwise, all QGraphicsItem
's support scaling.
- My main QGraphicsWidget (on which the grid is displayed) doesn't take up the whole width of the view, what is the best way to achieve this?
On the view, you can get the .viewport()
size, then just set the size of your graphics widget to the size of the viewport. You'll have to override the resizeEvent
on the QGraphicsView
to also resize your QGraphicsWidgets
whenever the view resizes.
- How would I go about making my QGraphicsGrid "responsive"?
For this, you'd probably be better off not using a grid and computing the placement of each item in your graphics scene manually. It depends somewhat on how you want your items placed. Are some widgets supposed to be below or next to others? Do you just want a tightly packed grid? Can an item span two grid lines? Does everything have to fit on a single "page", or is vertical scrolling allowed. You'll have to answer these questions first before you get any good answers. But generally, you know the size of the viewport. If you have a list of graphics items, you can just iterate through them and set their position based off the items you've already placed. Again, override the resizeEvent
on the graphics view so that you can re-compute item positions whenever the view resizes.