我需要创建一个有三种状态的按钮:
我想用这个按钮实现的逻辑是,无论何时单击此按钮,我都希望系统进入中间状态并等待事件。
其他方式,状态转换为SELECT COUNT(*)
FROM `messages`
WHERE `keyword_id` = [keyword.id] AND (`created_at` BETWEEN '[from_date]' AND '[to_date]')
,然后是unclicked --> intermediate -- > clicked
。
Qt是否支持实现这种按钮?如果是这样,怎么样?
答案 0 :(得分:2)
离你最近的是QCheckBox
。它已经有了一个属性:QCheckBox::setTristate
:
auto yourCheckBoxButton = new QCheckBox("Tristate button");
yourCheckBoxButton->setTristate(true);
您也可以在Designer上执行此操作(它位于属性列表的末尾)。
如果您不想使用QCheckBox
,每次按下按钮时修改的样式表和自定义属性都可以执行此操作:
auto pushButton = new QPushButton("Tristate button");
pushButton->setProperty("state", 0);
pushButton->setProperty("state-step", 1); // change to next state, 1 or -1
pushButton->setStyleSheet("QPushButton[state=\"0\"] { background: red; }"
"QPushButton[state=\"1\"] { background: grey; }"
"QPushButton[state=\"2\"] { background: blue; }");
connect(pushButton, &QPushButton::clicked, [ = ](bool) {
const int state = pushButton->property("state").toInt();
const int step = state == 0 ? 1 :
state == 2 ? -1 : pushButton->property("state-step").toInt();
pushButton->setProperty("state", state + step);
pushButton->setProperty("state-step", step); // update in case it changed
// Changing the property is not enough to choose a new style from the stylesheet,
// it is necessary to force a re-evaluation
pushButton->style()->unpolish(pushButton);
pushButton->style()->polish(pushButton);
});
其他更详细的选项是使用QProxyStyle
或重新实现QPushButton
类本身。