Important: Please read the Qt Code of Conduct -

Custom QGraphicsItem Explanation

  • Hi all,

    Just a quick question because i don get it.

    I have followed "This": Video that lets you create a Custom QGraphicsItem but i was a little bit puzzled by something i did.
    I built the project before i entered (line 8)"setFlag(ItemIsMovable);"
    if i click the Square it only changed the collor to red.
    but when release the mouse button it did not change it back into green.

    But when id do enter (line 8) "setFlag(ItemIsMovable);" it works like it supposed to.

    Can some one explain why it don't work without the setFlag option.

    @#include "square.h"
    #include <QGraphicsItem>
    #include <QDebug>

    Pressed = false;


    QRectF Square::boundingRect() const
    return QRectF(0,0,100,100);

    void Square::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    QRectF rec = boundingRect();
    QBrush brush(Qt::blue);



    void Square::mousePressEvent(QGraphicsSceneMouseEvent *event)
    Pressed = true;

    void Square::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
    Pressed = false;


  • Lifetime Qt Champion


    What happens if you call event->accept() in mousePressEvent ?

  • Hi Thanx for the response

    QT is not recognizing the accept()
    i can do a acceptedMouseButtons() but that is also not the solution.

  • Lifetime Qt Champion

    What do you mean by Qt doesn't recognize accept ? What did you write ?

  • If I understood the docs correctly then a graphics item should not get mouse events if a correct flag is not set.

    From "QGraphicsItem::​mousePressEvent()":
    "The event is QEvent::ignore()d for items that are neither movable nor selectable."

    And from "QGraphicsItem::​setFlags()":
    "By default, no flags are enabled."

  • Lifetime Qt Champion

    Right ! I've missed the flag part !

  • HI sorry for the late replay needed to work for some day's.

    oke i understand it now.

    The way the video explain it was more like "well we put this also into the mix just for fun"

    but it is essential to get the mouse events to set the flag selectebel or movable.

    Thanx allot for explaining that.

Log in to reply