Just yesterday a team mate asked me how to fake a gesture event on a desktop, say by clicking on a button, and I quickly wrote this example using Qt Designer form, a push button when clicked sends a tap gesture. Comments welcome :)

PS. Just remember: Gesture objects are not constructed directly by developers. They are created by the QGestureRecognizer object that is registered with the application; see QGestureRecognizer::registerRecognizer().

  1. #include "mainwindow.h"
  2. #include "ui_mainwindow.h"
  3. #include <QDebug>
  4. #include <QTapGesture>
  5. #include <QGestureEvent>
  6.  
  7. MainWindow::MainWindow(QWidget *parent) :
  8.     QMainWindow(parent),
  9.     ui(new Ui::MainWindow)
  10. {
  11.     ui->setupUi(this);
  12.     connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(gest()));
  13.     grabGesture(Qt::TapGesture);
  14. }
  15.  
  16. MainWindow::~MainWindow()
  17. {
  18.     ungrabGesture(Qt::TapGesture);
  19.     delete ui;
  20. }
  21.  
  22. void MainWindow::gest()
  23. {
  24.     QTapGesture *tapGes = new QTapGesture(this);
  25.     tapGes->setPosition(QPointF(5,5));
  26.     QList<QGesture *> tapGesTureList;
  27.     tapGesTureList.append(tapGes);
  28.     QGestureEvent event(tapGesTureList);
  29.     QCoreApplication::sendEvent(this, &event);
  30. }
  31.  
  32. bool MainWindow::event(QEvent *event)
  33. {
  34.     if (event->type() == QEvent::Gesture)
  35.     {
  36.         QGestureEvent *gestevent = static_cast<QGestureEvent*>(event);
  37.         if (QGesture *gest = gestevent->gesture(Qt::TapGesture))
  38.         {
  39.             QTapGesture *tapgest = static_cast<QTapGesture *>(gest);
  40.             qDebug() << "tap gesture got at: " << tapgest->position();
  41.         }
  42.     }
  43.     return true;
  44. }

Categories: