一、实现方式
为了通过监听disabled而改变图标,发现QPushButton和QToolButton并没有这个信号,所以需要去监听这个QEvent::EnabledChange事件即可得到这个状态。
二、代码
// TaskButton继承QPushButton
bool TaskButton::event(QEvent * e)
{
// 状态改变后,获取当前bool值
if (e->type() == QEvent::EnabledChange) {
emit customIsEnabled(isEnabled());
}
return QWidget::event(e);
}
// 连接
void CommandWidget::create()
{
TaskButton* btn = new TaskButton(this);
connect(btn, &TaskButton::customIsEnabled, this, &CommandWidget::onCustomIsEnabled);
}
// 调用类 CommandWidget
void CommandWidget::onCustomIsEnabled(bool isEnabled)
{
TaskButton *tb = dynamic_cast<TaskButton *> (sender());
if (!tb) {
return;
}
int a = tb->property("id").toInt();
if (isEnabled) {
tb->setIcon(m_idToPixmap[tb->property("id").toInt()]);
} else {
tb->setDisabledIcon(m_idToDisablePixmap[tb->property("id").toInt()]);
}
}