MildWolfie
MildWolfie

Reputation: 2532

How to determine if a QPushButton's released signal is the result of auto repeat or an actual mouse release

I have a QPushButton that performs two actions. One action should occur every time the button's pressed slot is called, including calls through autoRepeat. The second action should be performed starting when the button is first pressed, and ending only when it is no longer held by the User.

The problem is that autoRepeat triggers the button's pressed, released, and clicked signals. This results in the second action ending and starting again on every repeat rather then persisting for the duration the button is held. How can I determine if the button was actually released by the User using only the existing pressed and released slots?

Example code:

void MyClass::on_button_pressed()
{
    startHeldAction();
    doRepeatedAction();
}

void MyClass::on_button_released()
{
    stopHeldAction();
}

Upvotes: 4

Views: 943

Answers (1)

MildWolfie
MildWolfie

Reputation: 2532

I found that taking the following steps provided a relatively simple solution that did not require any additional event handling:

  1. Create a class member isHeld of type bool that defaults to false.
  2. Within the pressed slot, check isHeld. If if is false, set isHeld to true and call startHeldAction().
  3. Within the released slot, check the down property of the button. If it is false, set isHeld to false and call stopHeldAction().

Making these changes produces the following code:

void MyClass::on_button_pressed()
{
    if( !isHeld )
    {
        isHeld = true;
        startHeldAction();
    }
    doRepeatedAction();
}

void MyClass::on_button_released()
{
    if( !ui->button->isDown() )
    {
        isHeld = false;
        stopHeldAction();
    }
}

This works because isDown() will return true in the released slot unless the User has actually released the mouse button.

Upvotes: 1

Related Questions