Reputation: 2532
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
Reputation: 2532
I found that taking the following steps provided a relatively simple solution that did not require any additional event handling:
isHeld
of type bool that defaults to false.isHeld
. If if is false, set isHeld
to true and call startHeldAction()
.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