Created
February 9, 2018 14:40
-
-
Save gboeer/a00760b6d7af32c01357fb7ff76ad86a to your computer and use it in GitHub Desktop.
Enable dragging of a QT5 QGraphicsView with middle mouse button (or any other button than the default)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
So you want to use the QGraphicsView Drag Mode but with another mouse button than the default left click? | |
You can of course reimplement the mouse_move_event in a subclass but did you notice how ugly it is to implement | |
all the dragging functionality by yourself? | |
All you want to do is use another mouse_button with the existing dragging functionality | |
but there is no such thing as a setDraggingButton function. | |
Here we use a little hack which enables the dragging mode only temporarly when clicking a button of your choice and then | |
sends a left-click event which will trigger the standard dragging functionality of the QGraphicsView. | |
Keywords: QT5, Dragging, QGraphicsView | |
**/ | |
class MyGraphicsView : public QGraphicsView { | |
Q_OBJECT | |
bool eventFilter(QObject* object, QEvent* event); | |
}; | |
bool MyGraphicsView::eventFilter(QObject *object, QEvent *event) { | |
if (event->type() == QEvent::MouseButtonPress) | |
{ | |
QMouseEvent* mouse_event = static_cast<QMouseEvent*>(event); | |
// Enter here any button you like | |
if (mouse_event->button() == Qt::MiddleButton) | |
{ | |
// temporarly enable dragging mode | |
this->setDragMode(QGraphicsView::DragMode::ScrollHandDrag); | |
// emit a left mouse click (the default button for the drag mode) | |
QMouseEvent* pressEvent = new QMouseEvent(QEvent::GraphicsSceneMousePress, | |
mouse_event->pos(), Qt::MouseButton::LeftButton, | |
Qt::MouseButton::LeftButton, Qt::KeyboardModifier::NoModifier); | |
this->mousePressEvent(pressEvent); | |
} | |
else if (event->type() == QEvent::MouseButtonRelease) | |
{ | |
// disable drag mode if dragging is finished | |
this->setDragMode(QGraphicsView::DragMode::NoDrag); | |
} | |
Q_UNUSED(object) | |
return false; | |
} |
also working in pyqt. Just add installEventFilter on the both QGraphicsView and QGraphicsScene
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I run this code, but can not use in middle mouse for hand drag mode,
I use this code and promote it in to Graphics view.
Can you instruct to me, how I use this code