PDA

View Full Version : QGraphicsView - How to add item that is composed of more shapes



juracist
8th May 2014, 10:35
I have to add one component to QGraphicsView which is composed of more different shapes/items. Each component's view is defined by ordered list of different shapes:
1. Rectangle (0,0,100,100) -gray
2. Rectangle (5,5, 70,70) - yellow
3. Text (15,15) - black
10344

How can i compose item like that and add it to QGraphicsView?

I already tried with QGraphicsPathItem but it doesn't allows composition like this and more colors and so on..

anda_skoa
8th May 2014, 14:18
QGraphicsItemGroup

Cheers,
_

juracist
11th May 2014, 15:15
Answer to my first question was reimplementing all classes derived from QGraphicsPathItem to QGraphicsItem. Then, in overriden paint method from QGraphicsItem class, I added multiple draw methods (drawRect, drawText, etc.) and everything worked fine.

But now, I have another problem. Next step in my application is adding Pins to Component.


QGraphicsItemGroup

Cheers,
_

I've used QGraphicsPathItem as suggested in post above, but it also have some weird behaviour. Here is screenshot of QGraphicsItemGroup with 3 added items - 1 component and 2 pins.
10349

All of them (every item in group) should be moveable as whole composition, but every single item that was added to group should be also selectable.
Also, all the empty space that is rounded by rectangle line when group is selected shouldn't trigger any move or select action.
One more problem: it's not possible to select randomly items in group. Once the item is selected, it's necessary to click somewhere out of bounding (imaginary) group rectangle, and then other item can be selected again.

Here's code:


QGraphicsItemGroup *group = new QGraphicsItemGroup(0);
group->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable);
scene->addItem(group);
group->addToGroup(item);
group->addToGroup(pin);

Added after 36 minutes:

I'll answer myself:
All I needed to do is to set parent item to my pin (pin->setParent(item)) and set ItemIsMovable flag to false. Without even creating a QGraphicsItemGroup object.

wysota
12th May 2014, 12:32
Answer to my first question was reimplementing all classes derived from QGraphicsPathItem to QGraphicsItem. Then, in overriden paint method from QGraphicsItem class, I added multiple draw methods (drawRect, drawText, etc.) and everything worked fine.

If you have an item that is composed of other items then you should do exactly that -- use the parent-child relationship to compose the item from simple shapes. Otherwise you will be constantly modifying your implementation and adding more and more code making the class more and more complex while all you need is a proper object composition.