1

In my application a user is able to select a comport from a list of all available comports. This is to be done in a menu that is populated with QAction widgets. However, the current code does not show which port has been selected, and in order to make the application more intuitive, I would like to indicate which port has been selected, thus showing the user what state the program is in. By including some sort of icon (like a check mark, for example) in the menu right next to the selected port, it would be obvious which port has been selected. What is the correct way to do this?

My code:

# 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)

This code obviously doesn't do what I want, because it puts checkboxes next to each menu item. Additionally, it allows the user to check more than one comport at time, which is not at all desirable.

Check marks wanted, rather than checkboxes

ADB
  • 1,210
  • 4
  • 15
  • 23

1 Answers1

0

Coming to this years late, and in C++, but in the event someone down the line gets here, this is what I did (disclaimer: this is a bit of a hack):

  1. Keep a reference to the action that's currently selected
  2. When selected, set the checked and checkable flags to true for the selected item.
  3. Once the selection changes, remove the check from the selected action, and update the reference

This seems to allow for items to be checked, but only one item at a time. This solution really only works for trying to maintain a single selection.

// 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);
Hikash
  • 419
  • 3
  • 6