Custom QGraphicsItem Explanation



  • Hi all,

    Just a quick question because i don get it.

    I have followed "This":https://www.youtube.com/watch?v=hgDd2QspuDg&list=PL2D1942A4688E9D63&index=82 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>

    Square::Square()
    {
    Pressed = false;
    setFlag(ItemIsMovable);

    }

    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);

    if(Pressed)
    {
        brush.setColor(Qt::red);
    }
    else
    {
        brush.setColor(Qt::green);
    }
    
    painter->fillRect(rec,brush);
    painter->drawRect(rec);
    

    }

    void Square::mousePressEvent(QGraphicsSceneMouseEvent *event)
    {
    Pressed = true;
    update();
    QGraphicsItem::mousePressEvent(event);
    }

    void Square::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
    {
    Pressed = false;
    update();
    QGraphicsItem::mouseReleaseEvent(event);
    }

    @


  • Lifetime Qt Champion

    Hi,

    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()":http://doc.qt.io/qt-5/qgraphicsitem.html#mousePressEvent
    "The event is QEvent::ignore()d for items that are neither movable nor selectable."

    And from "QGraphicsItem::​setFlags()":http://doc.qt.io/qt-5/qgraphicsitem.html#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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.