PDA

View Full Version : Mouse event on a QGraphicsItem that is not in it's own class



xzyerasu
26th December 2012, 18:47
Let's say I create a QGraphicsItem (rectangle) in a QGraphicsScene (scene), without creating a class for the item:

Constructur of Mainwindow (.cpp):


ui->setupUi(this);
scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
rectangle = scene->addRect(0,0,100,100);


Is there a way to overwrite a mouse click on the rectangle and make something happen, even if it is not in another class?
What about showing a tooltip when hovering over it?

I hope the question is clear and not completely redundant.

lanz
27th December 2012, 08:31
I can think of one way of doing so without subclassing. You may create class that will be filtering mouse events and install it on the QGraphicsView via QObject::installEventFilter,
(you can't install it onto item itself, because it is not derived from QObject). But if you go this way you will be forced to map coordinates from view to item.

IMHO subclassing QGraphicsRectItem is much more clearer and easy way. It's not that hard! You'll need to override just a few protected methods.

wagmare
27th December 2012, 09:41
Let's say I create a QGraphicsItem (rectangle) in a QGraphicsScene (scene), without creating a class for the item:

Constructur of Mainwindow (.cpp):


ui->setupUi(this);
scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
rectangle = scene->addRect(0,0,100,100);


Is there a way to overwrite a mouse click on the rectangle and make something happen, even if it is not in another class?
What about showing a tooltip when hovering over it?

I hope the question is clear and not completely redundant.

u need to set void QGraphicsItem::setToolTip ( const QString & toolTip ) of the graphicsItem ... if u want to use the hover event hoverEnterEvent ( QGraphicsSceneHoverEvent * ) then u override the graphicsItem instead of using eventFilter ..

xzyerasu
27th December 2012, 17:04
Thank you, it worked great wit setToolTip. Now however, do you also know if there is a way to use the mouse clicks on this item? (to open a dialog box for example)

wysota
29th December 2012, 21:01
If you want, you can handle all events in the scene or in the view.