Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[Solved] QGraphicsObject with child groups mousePressEvent not firing



  • After lots of googling and testing I am stuck. I have a derived QGraphicsObject that contains a number of QGraphicsGroup's and QGraphicsItem's and for the life of me I am unable to get the mousePressEvent to fire for my object, interestingly enough my objects boundRect() does get called when I click the graphics view.

    The constructor of my QGraphicsItem looks something like this:

    @
    MyItem::MyItem(QGraphicsItem * parent) : QGraphicsObject(parent)
    {
    setFlags(QGraphicsItem::ItemIsSelectable);
    setHandlesChildEvents(true);

    _root = new QGraphicsItemGroup();
    _root->setParentItem(this);
    
    QGraphicsRectItem * item = new QGraphicsRectItem();
    item->setRect(0, 0, 100, 100);
    _root->addToGroup(item);
    

    }
    @

    I continue to add many more items but for readability lets assume I just have a rectangle that is 100x100. Next I override the boundRect() function:

    @
    QRectF MyItem::boundingRect() const
    {
    return QRectF(-50, -50, 50, 50);
    }
    @

    My object is being painted correctly but I simply do not get mouse events. I am using the default QGraphicsScene and QGraphicsView. I have tried all the combinations of setting setHandlesChildEvents on myself and _root, but that does not seem to make a difference. Any ideas?

    Thanks!



  • Could you show your declaration of your mouse event handler?



  • Definitely!

    @
    void MyItem::mousePressEvent(QGraphicsSceneMouseEvent * event)
    {
    if( event->button()==Qt::LeftButton )
    {
    // do something
    }
    }
    @



  • Ok, this is strange. I created a test app thinking I would post it here to demonstrate the problem however in my test app it works great so clearly it is something I am doing wrong. I'll post my solution once I find one here.



  • Found my problem. I was adding MyItem objects to a group and then adding that group to my scene, turns out if I set setHandlesChildEvents to false on my group then it allows MyItem to get the mouse events as normal.

    Hope this is helpful.


Log in to reply