Qt:菜单项旁边的复选标记

时间:2014-05-12 17:51:58

标签: qt pyqt5 qmenu qaction

在我的应用程序中,用户可以从所有可用组件的列表中选择一个组件。这将在一个填充了QAction小部件的菜单中完成。但是,当前代码没有显示选择了哪个端口,为了使应用程序更直观,我想指出选择了哪个端口,从而向用户显示程序所处的状态。通过包含某种类型在所选端口旁边的菜单中的图标(例如复选标记),很明显选择了哪个端口。这样做的正确方法是什么?

我的代码:

# Populate the serial port menu with all the available ports.
for port in comports(): 
    _port = QtWidgets.QAction(port[0], mainWindow)
    _port.setCheckable(True)   # WRONG!
    self.menuChoose_port.addAction(_port)
    _port.triggered.connect(self.comportSelect)

这段代码显然没有做我想要的,因为它会在每个菜单项旁边放置复选框。此外,它允许用户在时间检查多个comport,这是完全不可取的。

Check marks wanted, rather than checkboxes

1 个答案:

答案 0 :(得分:0)

来到今年晚些时候,并使用C ++,但是如果有人直接来到这里,这就是我所做的(免责声明:这有点hack):

  1. 保留对当前选定动作的引用
  2. 选中后,将所选项目的选中和可检查标志设置为true。
  3. 选择更改后,请从所选操作中删除检查,然后更新引用

这似乎允许检查项目,但一次只能检查一项。此解决方案真的仅适用于尝试维护单个选择的情况。

// in the header:
QAction *selectedAction = nullptr;

// in the cpp file
QAction *act = new QAction("exampleItem");

connect(act, &QAction::triggered, [this, act] {
  if (selectedAction != nullptr) {
    selectedAction->setChecked(false);
    selectedAction->setCheckable(false);
  }
  act->setCheckable(true);
  act->setChecked(true);
  selectedAction = newAction;
})

menu->addAction(act);