Skip to content

Instantly share code, notes, and snippets.

@jniemann66
Last active June 4, 2020 06:01
Show Gist options
  • Save jniemann66/a31007cbaaca5ed511cd96bf80f644f2 to your computer and use it in GitHub Desktop.
Save jniemann66/a31007cbaaca5ed511cd96bf80f644f2 to your computer and use it in GitHub Desktop.
Qt: Event Filter for Long Mouse Press (hold mouse for >= 1sec)
// LongPress: event filter Object for detecting Mouse pressed down for 1 second or more
// when triggered, it executes callback function supplied in the constructor
// usage:
/*
someButton->installEventFilter(new LongPress(this, [this] {
// do some stuff
}));
*/
class LongPress : public QObject{
Q_OBJECT
public:
LongPress(QObject* parent, std::function<void()> f) : QObject(parent), f(f)
{
t.setInterval(1000);
connect(&t, &QTimer::timeout, this, f);
};
protected:
bool eventFilter(QObject* obj, QEvent* event) override
{
if(event->type() == QEvent::MouseButtonPress) {
t.start();
} else if(event->type() == QEvent::MouseButtonRelease) {
t.stop();
}
return QObject::eventFilter(obj, event);
}
private:
std::function<void()> f;
QTimer t;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment