Qt中的切换按钮对

问题描述

我正在从两个QPushButton建立一个简单的开关。刚开始时,仅启用一个(假设按钮1),当您单击它时,在启用按钮2时将其禁用。如果您单击按钮2,它将被禁用,按钮1被启用。

这是.cpp代码

#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);
}

似乎很简单,并且在一定程度上有效。当按钮保持一致的启用/禁用状态时,当我真正快速地切换某个时间时,禁用的背景色不会变暗。这是一个示例:

enter image description here

仅通过跳出即可自行修复背景颜色,但是我想知道是否忽略了某些内容,并且有一种避免这种行为的方法

编辑:我做了一些测试,发现它与配对按钮无关,但是如果您双击得足够快,即使使用一个按钮也可能发生(可能我在做类似的事情而没有注意到)。

解决方法

我能够重现此行为:单击按钮,而鼠标悬停在按钮上时,有时会导致伴随悬停的动画无法正确完成。

在禁用按钮后的某个时间更新禁用按钮会清除错误的动画。在禁用“ pushButton”的函数中添加以下行可清除错误的动画: std::thread([&]{ std::this_thread::sleep_for(std::chrono::milliseconds(500)); pushButton->update();}).detach();

在调用setEnabled(false);之后立即更新禁用按钮并不能阻止这种行为,但是我无法找到有关如何在qt源中实现鼠标悬停动画的任何信息。

要解决此问题,您可以在一段时间后对按钮进行适当的延迟更新,例如通过QTimer或类似工具。