开发者

Event filter on QGraphicsItem

开发者 https://www.devze.com 2023-01-06 20:02 出处:网络
Is it possible to have an开发者_C百科 event filter on a QGraphicsItem? Eventfilter has a param that gives you a QObject, but since QGraphicsItem isn\'t derived from QObject, then how would it work?QGr

Is it possible to have an开发者_C百科 event filter on a QGraphicsItem? Eventfilter has a param that gives you a QObject, but since QGraphicsItem isn't derived from QObject, then how would it work?


QGraphicsItem's are not QObjects, but they still receive events, managed by their QGraphicsScene. And it also supports event filtering. QGraphicsItem::installSceneEventFilter( QGraphicsItem* filterItem ) installs another item to receive events. Override sceneEventFilter() in the filter item to handle them. It works analoguously to QObject::eventFilter. Important: The item you install the filter on must be already added to a scene to make it work.

If the filter item should do nothing else but filter, i think the easiest way is to derive from QGraphicsItem, implement paint() do no nothing and boundingRect() returning an empty rect. And reimplement sceneEventFilter of course.

Also note that some event classes change in QGraphicsView context, e.g. QMouseEvent becomes QGraphicsSceneMouseEvent, so make sure to filter for the right thing.


Edit: Use QGraphicsItem::installSceneEventFilter as suggested in @Frank's answer. Example:

QGraphicsScene scene;
QGraphicsEllipseItem *ellipse = scene.addEllipse(QRectF(-10, -10, 20, 20));
QGraphicsLineItem *line = scene.addLine(QLineF(-10, -10, 20, 20));
line->installSceneEventFilter(ellipse);
// line's events are filtered by ellipse's sceneEventFilter() function.
ellipse->installSceneEventFilter(line);
// ellipse's events are filtered by line's sceneEventFilter() function.

The first thing that popped into my mind was this:

Create a new class, derived from both QGraphicsItem and QObject, since these are unrelated (as far as a glance at the docs tells me), you should have what you wanted.

.... But then I looked at the docs more closely and found QGraphicsObject, which is probably exactly what you want, it even already has the member eventFilter


No. You can not install an event filter to QGraphicsItem directly since it's not a QObject. If you are deriving your own QGraphicsItem, inherit from QGraphicsObject so it will gain QObject functions.

One possibility is use http://doc.trolltech.com/latest/qgraphicsitem.html#installSceneEventFilter but it;s more limited since it requires the handler to be a QGraphicsItem too.


In case you are subclassing a QGraphicsView you have also the option to just reimplement any of the many ...Event() functions. In such cases you do not need an eventfilter.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号