I'm subclassing QGraphicsView and what I'd like to do is: if the MidButton is pressed while the mouse is moving then we do as if we were using the regular QGraphicsView course of action but with the left button pressed which is sliding the image.
I tried coding it but it doesn't seems to work and I don't know why.
void MyQGraphicsView::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() == Qt::MidButton)
{
QMouseEvent event2(QEvent::MouseMove, event->pos(), Qt::NoButton, Qt::LeftButton, Qt::NoModifier);
QGraphicsView::mouseMoveEvent(&event2);
}
}
Any help would be appreciated.
Edit: removed obvious error as pointed out by Anthony.
There are a few problems. First, the test condition should use testFlags
rather than ==
. Second, you were creating the event with Qt::MidButton
and it should be Qt::LeftButton
. Last, you also need to do a similar test for mousePressEvent
(so that QGraphicsView can know to initiate the hand drag).
void mousePressEvent(QMouseEvent *event)
{
if (event->buttons().testFlag(Qt::MidButton))
{
QMouseEvent event2(QEvent::MouseButtonPress, event->pos(), Qt::LeftButton, Qt::LeftButton, Qt::NoModifier);
// do default behavior as if you pressed the left button
QGraphicsView::mousePressEvent(&event2);
}
else
{
QGraphicsView::mousePressEvent(event);
}
}
void mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons().testFlag(Qt::MidButton))
{
QMouseEvent event2(QEvent::MouseMove, event->pos(), Qt::NoButton, Qt::LeftButton, Qt::NoModifier);
// do default behavior as if you pressed the left button
QGraphicsView::mouseMoveEvent(&event2);
}
else
{
QGraphicsView::mouseMoveEvent(event);
}
}