c++ - 如何使用Qt实现三态按钮

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

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

  • 未点击
  • 中级
  • 点击

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

换句话说,当状态转换为 unclicked --> intermediate --> clicked 然后 clicked --> intermediate -->unclicked

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

最佳答案

离你最近的是QCheckBox。它已经有一个属性:QCheckBox::setTristate :

auto yourCheckBoxButton = new QCheckBox("Tristate button");
yourCheckBoxButton->setTristate(true);

您也可以在设计器上执行此操作(它位于属性列表的末尾)。

如果你不想使用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 类本身。

关于c++ - 如何使用Qt实现三态按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45030504/

相关文章:

C++:使用 boost lambda 获取 std::tr1::unordered_map 中的最大值

c++ - 使用 OpenGL 和 QT 进行纹理映射 - C++

qt - 如何在 addItem 或 itemChange 上从 QGraphicsScene 获取通知?

python - 更新 tkinter Label 以在我的 python GUI 上显示文本文件,一次一行

user-interface - Unity3D - 特定 UI 元素的屏幕截图

c++ - MS Visual Studio 2005 C++ 异常处理

c++ - 如何从一个到另一个减去 std::unordered_map vector 元素并在 C++ 中更新它?

c++ - 如何在标准字符串中搜索/查找和替换?

python - PyQt4中如何检测cellwidget用户点击QTableWidget的行号和列号?

java - 单击添加 GUI 元素仅有效一次