0

I'm using QGraphicsScene and I would like to have some items which emit signals when they are moved around.

Unfortunately, QGraphicsPixmapItem doesn't have any signals, so I subclassed it:

class InteractiveGraphicsPixmapItem : public QObject, public QGraphicsPixmapItem
{
    Q_OBJECT

public:
    InteractiveGraphicsPixmapItem();

    InteractiveGraphicsPixmapItem(QPixmap pm) : QGraphicsPixmapItem(pm)
    {
        setFlag(QGraphicsItem::ItemIsMovable, true);
        setAcceptedMouseButtons(Qt::LeftButton|Qt::RightButton);
    }

private:
    void mouseMoveEvent(QGraphicsSceneMouseEvent *);

signals:
    void moved_by_mouse(QPointF newpos);

};


InteractiveGraphicsPixmapItem::InteractiveGraphicsPixmapItem()
{
}

void InteractiveGraphicsPixmapItem::mouseMoveEvent(QGraphicsSceneMouseEvent *)
{
    emit moved_by_mouse(this->pos());
}

However, it is not movable. If I change it back into a QGraphicsPixmapItem in the main program, and call item->setFlags(QGraphicsItem::ItemIsMovable); it becomes movable. For my custom class, it doesn't.

item = new InteractiveGraphicsPixmapItem(QPixmap(":/img/icon.png"));
scene->addItem(item);
item->setFlags(QGraphicsItem::ItemIsMovable);

A similar question was asked about selectability, and it was suggested that the setAcceptedMouseButtons(Qt::LeftButton|Qt::RightButton); must be added to the constructor. It didn't help in my case.

Community
  • 1
  • 1
vsz
  • 4,811
  • 7
  • 41
  • 78

1 Answers1

2

If you override the mouseMoveEvent, and don't call the base class's function, it won't move and you'll have to handle it yourself.

However, simply calling the base class function is all you need here

void InteractiveGraphicsPixmapItem::mouseMoveEvent(QGraphicsSceneMouseEvent* evt)
{
    QGraphicsPixmapItem::mouseMoveEvent(evt);
    emit moved_by_mouse(this->pos());
}

Also note that if you override one of the mouse events (press / release / move) you should also handle the others too.

vsz
  • 4,811
  • 7
  • 41
  • 78
TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85