Reputation: 310
Item.h:
class Item:public QGraphicsRectItem
{
public:
Item(const QRectF & rect, QGraphicsItem * parent = 0);
void mousePressEvent(QGraphicsSceneMouseEvent * event);
void mouseMoveEvent(QGraphicsSceneMouseEvent * event);
~Item();
};
Item.cpp:
Item::Item(const QRectF & rect, QGraphicsItem * parent)
:QGraphicsRectItem(rect, parent)
{
}
void Item::mousePressEvent(QGraphicsSceneMouseEvent * event){
qDebug("press");
QGraphicsRectItem::mousePressEvent(event);
event->accept();
}
void Item::mouseMoveEvent(QGraphicsSceneMouseEvent * event){
qDebug("move");
}
Item::~Item()
{
}
main.cpp:
#include "mainwindow.h"
#include <QApplication>
#include "QGraphicsView"
#include "QGraphicsScene"
#include "item.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// MainWindow w;
// w.show();
auto item = new Item(QRectF(QPointF(),QSize(100,150)));
auto scene = new QGraphicsScene;
scene->addItem(item);
auto view = new QGraphicsView(scene);
view->setMinimumSize(QSize(800,600));
view->scene()->setSceneRect(QRectF(QPointF(),view->size()));
view->show();
return a.exec();
}
I have read the doc about QGraphicsItem::mousePressEvent, which says "If you do reimplement this function, event will by default be accepted (see QEvent::accept()), and this item is then the mouse grabber. This allows the item to receive future move, release and doubleclick events." Now I have reimplemented it. Why doesn't it work?
Upvotes: 0
Views: 687
Reputation: 1
If you just want a move event from the mouse without a mouse button press, you can use virtual void QGraphicsItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) instead.
Upvotes: 0
Reputation: 1
Enable flags to use the functionalities
item ->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable);
item ->setAcceptHoverEvents(true);
item ->setAcceptedMouseButtons(Qt::LeftButton);
Upvotes: 0
Reputation: 12901
When the mouse event is created it is set as accepted. Depending on the flags you have set to your item, the default mousePressEvent
implementation might reject it.
In your case you are calling the default implementation which might reject the mouse press event. If that is the case, the mouseMoveEvent
will never be called.
You should read this interesting article about events.
Upvotes: 2