Nominate our 2022 Qt Champions!

How can i get a mouse event(clicked,pressed,released,etc...)in my custom graphicsitem contained by a QGraphics View?

  • Hello!

    I got a problem while using QGraphicsView:

    I derived a subclass from QGraphicsObject class, and implemented it with my own purpose. I want the instance of the subclass can be selected and deselected.

    I overrided the QGraphicsItem::​mousePressEvent and QGraphicsItem::​mouseReleaseEvent:

    In the override function of QGraphicsItem::​mousePressEvent, I implemented nothing because I don't know what to do,and because the help documents says "If you do reimplement this function, event will by default be accepted (see QEvent::accept()), and this item is then the mouse grabber.".

    In the override function of QGraphicsItem::​mouseReleaseEvent, I simply set the item's selected property to TRUE by calling function QGraphicsItem::​setSelected and passing true to it's parameter.

    well,this is all my key implementation.But when I test it, it doesn't works! The function QGraphicsItem::​isSelected still returns false after I clicked a mouse left button on the item of subclass.In debug session, a breakpoint in the override function of QGraphicsItem::​mousePressEvent can not be reached when I click a mouse left button.

    So,what's wrong with my implementation?Can you help me please?thx!

    BTW:I can't post my source code currently because they are in my office computer, and now I'm in my home. I will post them later if you need them.

    reply to Rondog(I can’t reply the post by clicking reply button on this forum,so I can only reply you on this way,sorry! and I hate this weak forum!):

    thx Rondog!

    I'll try your instrument later in my office.

    well there is another question I doubted: Does the event not work in QGraphicsItem ?

  • I haven't use the ones in QGraphicsItem but I have done this by sub-classing the mouse events in QGraphicsView. This would prevent problems like getting a mouse-down event on one item, a move event on another, and a mouse up on a third.

    declaration in subclass to QGraphicsView

    virtual void mouseDoubleClickEvent(QMouseEvent *event);
    virtual void mouseMoveEvent(QMouseEvent *event);
    virtual void mousePressEvent(QMouseEvent *event);
    virtual void mouseReleaseEvent(QMouseEvent *event);

    implementation for QGraphicsView. In my case they are all QGraphicsPixmapItems

    void TView::mousePressEvent(
    QMouseEvent *event)
    QPointF point;
    QGraphicsItem *graphics_item;


    d_mouse_down_buttons = event->buttons();
    point = this->mapToScene(event->pos());

    d_moving_item_moved = false;
    d_moving_item = 0;

    if((d_mouse_down_buttons & Qt::LeftButton) == Qt::LeftButton)
    graphics_item = d_graphics_scene->itemAt(point,this->transform());

    d_moving_item = reinterpret_cast<QGraphicsPixmapItem*>(graphics_item);

    d_moving_item_last_position = point;

Log in to reply