How to Implement Custom Optimized MouseDoubleClickEvent Function in Qt

If you were unaware that Qt’s default mouseDoubleClickEvent isn’t exactly optimized, as that is the nature of the beast, so when you override it, it will slow everything down. So the only thing you can do is write your own mouse double click event handler.

I won’t be using custom events and any fancy delegates and stuff. Don’t touch system pointers or direct memory unless you have to. This is a very simple implementation compared to the big picture.

To begin, you must understand that a mouse double click is essentially this sequence: mousePress, mouseRelease, mouseDoubleClickFlag, mouseRelease.

So to implement that, you would create a var to keep track of how many clicks you’ve pressed. You also need a counter to keep track of time between first click and second click. You also need a flag variable so you can trigger your custom mouseDoubleClickEvent function.

qint32 mouseClicks;
qint32 doubleClickTime;
bool triggerDoubleClick;

Then, you would create a QTimer to keep track of how long it takes between 0 mouseClicks and 2 mouseClicks. You don’t want to use QTime or QElapsedTimer because on Windows those are limited to 32-bit and milliseconds are not guaranteed to be accurate, and will overload quite fast. QTime and QElapsedTimer also are bound to the system clock in Windows, which isn’t guaranteed accurate. So use QTimer because you only want short bursts of numbers.

QTimer * tmrDoubleClick;

You need to create a slot to hook the QTimer’s timeout() signal:

private slot:
  void timedDoubleClick();

Don’t forget to initialize your variables. And then connect the QTimer’s signal to the slot:

mouseClicks = 0;
doubleClickTime = 0;
triggerDoubleClick = false;

tmrDoubleClick = new QTimer();
connect(tmrDoubleClick, SIGNAL(timeout()), this, SLOT(timedDoubleClick()));

This is what you do in your slot:

void MyApp::timedDoubleClick()
{
  doubleClickTime++;

  //NOTE the number 15 is arbitrary and not necessarily in milliseconds, change to your desire
  if (doubleClickTime > 15)
  {
    tmrDoubleClick->stop();
    doubleClickTime = 0;
    triggerDoubleClick = false;
  }
}

So in your customized overriden mousePressEvent function, do this:

void MyApp::mousePressEvent(QMouseEvent *e)
{
  triggerDoubleClick = false;

  if (mouseClicks == 0)
    tmrDoubleClick->start(16); //60 frames per second or 60Hz refresh rate

  mouseClicks++;

  if (mouseClicks > 1)
  {
    mouseClicks = 0;

    //essentially, if user clicks twice before QTimer stops, then its a go!
    if (doubleClickTime < 15)
      triggerDoubleClick = true;
  }
}

And then in your custom overriden mouseReleaseEvent function do this:

void MyApp::mouseReleaseEvent(QMouseEvent *e)
{
  if (triggerDoubleClick == true)
  {
    triggerDoubleClick = false;

     //do your double click stuff here
  }
}

And hopefully it runs really fast. You’re welcome.

CategoriesQt