【问题标题】:How to implement a tri state button using Qt如何使用 Qt 实现三态按钮
【发布时间】:2017-12-15 06:39:38
【问题描述】:

我需要创建一个具有三种状态的按钮:

  • 未点击
  • 中级
  • 点击

我想用这个按钮实现的逻辑是,每当点击这个按钮时,我希望系统进入中间状态并等待一个事件。

当状态转换为unclicked --> intermediate -- > clicked然后clicked --> intermediate -->unclicked时。

Qt 支持实现这种按钮吗?如果有,怎么做?

【问题讨论】:

  • 如何使用普通按钮并为中间状态赋予不同的颜色(或以某种方式改变外观)?
  • 如果您只想遍历所有状态,那么只需创建一个按钮并在内部创建一个状态值 0,然后每次单击只需将 1 向左或向右移动:clicked -> state <<=1 | state >>=1 然后你有 3 个状态,0 未点击,1 不确定,2 被点击
  • 甚至可以尝试重新实现 QPushButton

标签: c++ qt user-interface qpushbutton tri-state-logic


【解决方案1】:

您最近的地址是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 类本身。

【讨论】:

  • 三态正在改变状态,就像A -> B -> C -> A...如果我没记错的话,不是吗?不像问的那样A -> B -> C -> B -> A
  • @ymoreau 感谢您指出这一点,我已经更新了答案以涵盖它
猜你喜欢
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
  • 2012-02-12
  • 1970-01-01
相关资源
最近更新 更多