QShortcut and Mouse Event
-
I hope somebody can help me. I want to include a mouse event in a shortcut to perform a certain action. By example Ctrl+Mouse Single Click or Shift + Mouse Double Click.
Thanks.
-
I don't think that's possible (by now). But it is quite easy to implement by overriding the mouse event handlers or using event filters.
-
Thanks for your reply. Could you provide me an example?
-
Perhaps you could also leverage [[doc:QGesture]] instead of QShortcut. See the "Gestures Programming":/doc/qt-5.0/gestures-overview.html document.
However, clicks are usually done on a specific widget, and there is makes sense to simply handle the mouse event yourself directly.
-
[quote author="Tweety" date="1334306908"]Thanks for your reply. Could you provide me an example? [/quote]
There should be some code somewhere here lying around... here you go.
@
class MouseShortcut : public QObject
{
Q_OBJECTpublic:
enum ClickType
{
SingleClick,
DoubleClick
};MouseShortcut(MouseShortcut::ClickType type, Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers, QObject *parent = 0) : QObject(parent) { type_ = type; buttons_ = buttons; modifiers_ = modifiers; doubleClickFilter_.setSingleShot(true); doubleClickFilter_.connect(&doubleClickFilter_, SIGNAL(timeout()), this, SIGNAL(activated())); }
signals:
void activated();protected:
bool eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress)
{
if (type_ == MouseShortcut::SingleClick)
{
QMouseEvent mouseEvent = static_cast<QMouseEvent>(event);
if ((buttons_.testFlag(mouseEvent->button())) &&
(modifiers_ == mouseEvent->modifiers()))
{
doubleClickFilter_.start(QApplication::doubleClickInterval());
}
}
}
else if (event->type() == QEvent::MouseButtonDblClick)
{
if (type_ == MouseShortcut::SingleClick)
{
doubleClickFilter_.stop();
}
else
{
QMouseEvent mouseEvent = static_cast<QMouseEvent>(event);
if ((buttons_.testFlag(mouseEvent->button())) &&
(modifiers_ == mouseEvent->modifiers()))
{
emit activated();
}
}
}return QObject::eventFilter(object, event); }
private:
MouseShortcut::ClickType type_;
Qt::MouseButtons buttons_;
Qt::KeyboardModifiers modifiers_;
QTimer doubleClickFilter_;
};MouseShortcut *scA = new MouseShortcut(MouseShortcut::SingleClick,
Qt::LeftButton,
Qt::ControlModifier);
MouseShortcut *scB = new MouseShortcut(MouseShortcut::DoubleClick,
Qt::LeftButton | Qt::RightButton,
Qt::AltModifier | Qt::ShiftModifier);QObject::connect(scA, SIGNAL(activated()), ...);
QObject::connect(scB, SIGNAL(activated()), ...);widget.installEventFilter(scA); // widget-local shortcut
application.installEventFilter(scB); // application-wide shortcut
@
Snippet to terminal.