I'm building a simple switch from two QPushButton
. At the beginning, only one is enabled (let's say button 1) and when you click on it, it's disabled while button 2 is enabled. If you click on button 2, it's disabled and button 1 is enabled.
This is the .cpp code:
#include "SwitchButton.h"
#include "ui_SwitchButton.h"
SwitchButton::SwitchButton(QWidget * parent,
bool initialStatus,
const QString & trueText,
const QString & falseText)
: QWidget(parent), ui(new Ui::SwitchButton)
{
ui->setupUi(this);
ui->trueButton->setText(trueText);
ui->falseButton->setText(falseText);
// NOTE: Redundant, emits the corresponding signal while constructed
if (initialStatus)
on_trueButton_clicked();
else
on_falseButton_clicked();
}
SwitchButton::~SwitchButton()
{
delete ui;
}
void SwitchButton::on_trueButton_clicked()
{
ui->trueButton->setEnabled(false);
ui->falseButton->setEnabled(true);
emit changeStatus(true);
}
void SwitchButton::on_falseButton_clicked()
{
ui->falseButton->setEnabled(false);
ui->trueButton->setEnabled(true);
emit changeStatus(false);
}
Seems pretty straigthforward and it works to a certain extent. While the buttons keep consistent enabled/disabled states, when I switch really fast sometime the background color of the disabled one doesn't become darker. Here's an example:
Simply tabbing out makes the background color fix itself, but I was wondering if I overlooked something and there's a way to avoid this behaviour.
EDIT: I did a bit more testing and found out it has nothing to do with the pairing button but happens even with a single button if you double click fast enough (probably I was doing something like that without noticing).
I was able to reproduce the behaviour: Clicking the button, while the mouse stays hovered over the button sometimes leads to the animation that comes with the hovering not being finished properly.
Updating the disabled button some time after it was disabled clears the wrong animation. Adding the following line in the function that disables "pushButton" cleared the wrong animation:
std::thread([&]{ std::this_thread::sleep_for(std::chrono::milliseconds(500)); pushButton->update();}).detach();
Updating the disabled button immediately after a call to setEnabled(false);
doesn't prevent this behaviour, but I wasn't able to find anything about how the mouse hover animation is implemented in the qt sources.
For a workaround, you could implement a proper delayed update of the buttons after some time, e.g. via a QTimer or similar.