Brett Stottlemyer
Brett Stottlemyer

Reputation: 2852

QGraphicsWidget vs. QGraphicsLayoutItem

I'm working with QGraphicsView/Scene for the first time. This is in PyQt, but except for the fact that Python is different with multiple inheritance, I think this is a generic Qt question.

I started out by creating a couple of QGraphicsItem overloads as building blocks. Once I had those working the way I wanted, I wanted to try to combine them and was unpleasantly surprised to find that I couldn't use the in QGraphicsLayouts. This is due to the fact the QGraphicsLayouts take items that inherit from QGraphicsLayoutItem, and QGraphicsItems are inherited by QGraphicsLayoutItems, which are in turn inherited by QGraphicsWidgets.

There is a graphicsItem property of QGraphicsItem/QGraphicsWidget, but looking at the code, I don't think I can assign my Item's to this property and have them work properly. I did find this example, but strangely enough it has examples that inherit from both classes. Pretty confusing to me.

So I'm trying to find the easiest way to get my Items working in Layouts. Is there an easier way to do this than rewriting and inheriting from one of this two classes?

Secondary question, is there a rule of thumb for when you should inherit from QGraphicsWidget vs when you should inherit from QGraphicsLayoutItem?

Extra credit for explaining when sizeHint vs. boundingRect are used.

Appreciate the help, Brett

Upvotes: 3

Views: 3888

Answers (1)

baysmith
baysmith

Reputation: 5202

The easiest way to get items working in layouts is to change the inheritance to QGraphicsWidget and override the setGeometry() and sizeHint() methods. Should be a simple change since your items will still be QGraphicsItems through the inheritance ancestry.

The Qt Graphics View framework is designed to be as lightweight as possible. Thus there are many choices for assembling items with different capabilities. If the sizes of items to be in layouts are not a concern, you can inherit from QGraphicsWidget. Otherwise, inherit from QGraphicsLayoutItem (unless you need the extra capabilities of QGraphicsWidget). Since you can't multiply inherit from PyQt classes, you'll have to use composition for creating an item controlled by the QGraphicsLayoutItem, like in the example you referenced.

The boundingRect() method is used by the scene to manage items. The sizeHint() method is used by the layouts to determine the size of layout items. The shape() method is used by the scene to more precisely determine the location of items (for collisions, hit tests, etc).

Upvotes: 4

Related Questions