Reputation: 117
I know how to pass events from qgraphicsview to qgraphicsitem. But the problem is after executing the mouseEvent of item ,i have to execute the mouse event of the view which is not desirable in my case. so,the question is: "Is there a smart way to know if mousePress is on an item or on an empty space?"
Edit:The working code:
#include <QtGui>
class CustomView : public QGraphicsView
{
protected:
void mousePressEvent(QMouseEvent *event)
{
QGraphicsView::mousePressEvent(event);
qDebug() << "Custom view clicked.";
}
};
class CustomItem : public QGraphicsRectItem
{
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event)
{
qDebug() << "Custom item clicked.";
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CustomItem item;
item.setRect(20, 20, 60, 60);
QGraphicsScene scene(0, 0, 100, 100);
scene.addItem(&item);
CustomView view;
view.setScene(&scene);
view.show();
return a.exec();
}
Appling the same concept in a qgraphics scene instead of view
#include <QtGui>
class CustomScene : public QGraphicsScene
{
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if(itemAt(event->scenePos()))
QGraphicsScene::mousePressEvent((event));
else
qDebug() << "Custom view clicked.";
}
};
class CustomItem : public QGraphicsRectItem
{
protected:
void mousePressEvent(QGraphicsSceneMouseEvent *event)
{
qDebug() << "Custom item clicked.";
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CustomItem item;
item.setRect(20, 20, 60, 60);
CustomScene scene;
//scene().set
scene.addItem(&item);
QGraphicsView view;
view.setScene(&scene);
view.show();
return a.exec();
}
Upvotes: 0
Views: 1234
Reputation: 2752
To determine wether mouse event occured on item or not you can use QGraphicsView::itemAt:
void CustomView::mousePressEvent(QMouseEvent *event)
{
if (itemAt(event->pos()))
// Click on item
else
// Click on empty space
...
}
Upvotes: 2
Reputation: 40512
There are 3 correct ways to solve your task:
1.
Reimplement QGraphicsView::mousePressEvent
and use QGraphicsView::itemAt
to find clicked item.
2.
Subclass QGraphicsScene
and reimplement QGraphicsScene::mousePressEvent
. Its argument event
contains position in scene coordinates, and you can use QGraphicsScene::itemAt
to determine which item has been clicked.
3.
Subclass QGraphicsItem
(or any derived class) and reimplement QGraphicsItem::mousePressEvent
. It will be called only if this element was clicked.
Upvotes: 3