سؤال

I'm writing a program that uses the Qt Graphics View framework. I have subclassed QGraphicsItem to a class that includes other QGraphicsItem (or other subclasses of it). This class is the parent of the included QGraphicsItem; the idea is to work with composite objects.

From the docs it seems to be a conflict in what I try to achieve:

  • Calling ignore() in mousePressEvent will make my object unmovable. I want to move it.
  • Calling accept() in mousePressEvent will prevent the event from being propagated to the child object. Some of the child objects should react to mouse events.

How can I make this work?

هل كانت مفيدة؟

المحلول

I think your interpretation of the documentation is incorrect.

Calling ignore() in mousePressEvent will make my object unmovable.

I don't believe that is true. To me it looks like calling ignore() is like the object saying "I have assessed this event. I have taken all actions I want to in response to this event. I have also decided it was not intended for me, so I will now pass it on to the next object underneath me". I can't find anything which suggests the ignore event will unset the QGraphicsItem::ItemIsMovable flag (which is what decides if the QGraphicsItem is movable or not).

I don't see why you couldn't make your object move and ignore() the event, but I would advise that this is not a sensible approach (in most instances: obviously you may have cause for it).

Calling accept() in mousePressEvent will prevent the event from being propagated to the child object.

I believe this is true, but the parent can still modify its children. My understanding is calling accept() is like the object saying "I have assessed this event. I have taken all actions I want to in response to this event (which may include modifying my children). I have also decided that the event was intended for me, so I will not be passing the event on".

نصائح أخرى

In your parent QGraphicsItem, you might try to

MyObject::mousePressEvent ( QGraphicsSceneMouseEvent * event )
{
    QGraphicsItem::mousePressEvent(event);
    event->ignore();
}

This would allow normal processing of the mouse event (i.e. make your object moveable), but then ignoring it so that it is propagated.

The logic would need to be more robust, though, because there is a high risk of side effects if a parent and child respond to the same mouse event.

Send QCoreApplication::postEvent(child, mouseEvent) to child objects.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top