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.