3

I am trying to make my choices from QMenu to be checkable in a way that only one might be selected at time and first item is set checked by default (this works actually).

Here is a snippet of my code:

paymentType = QMenu('Payment Type', self)
paymentType.addAction(QAction('Cash', paymentType, checkable=True, checked = True))
paymentType.addAction(QAction('Noncash Payment', paymentType, checkable=True))
paymentType.addAction(QAction('Cash on Delivery', paymentType, checkable=True))
paymentType.addAction(QAction('Bank Transfer', paymentType, checkable=True))
menu.addMenu(paymentType)

Any suggestions? Thanks!

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
New2coding
  • 715
  • 11
  • 23

1 Answers1

6

A possible option is to use QActionGroup and activate the exclusive property

import sys
from PyQt5.QtWidgets import *

class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        QMainWindow.__init__(self, *args, **kwargs)
        menu = self.menuBar()
        paymentType = QMenu('Payment Type', self)
        group = QActionGroup(paymentType)
        texts = ["Cash", "Noncash Payment", "Cash on Delivery", "Bank Transfer"]
        for text in texts:
            action = QAction(text, paymentType, checkable=True, checked=text==texts[0])
            paymentType.addAction(action)
            group.addAction(action)
        group.setExclusive(True)
        group.triggered.connect(self.onTriggered)
        menu.addMenu(paymentType)

    def onTriggered(self, action):
        print(action.text())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Is there any way to proceed with self.menuBar() as property of QMainWindow class instead of creating QMenuBar? If so, the implementation would be something like: menu = self.menuBar() and then consequently menu.addMenu(paymentType)? I tried this and it does not seem to be working? Thanks – New2coding Jan 25 '18 at 17:25
  • @New2Python It seems strange to me, I have placed an example using QMainWindow and it works correctly, if even with the example it has a problem then I will need you to show a code that I can use. – eyllanesc Jan 25 '18 at 17:32
  • You are right, I missed self argument of QMenu() in that context. Now it works. Thanks! – New2coding Jan 25 '18 at 17:38
  • Any suggestion how to retrieve isChecked() information? Imagine the case when user wants it to be set to cash by default and thus will not trigger the button, however, on other event we would need to extract this information and retrieve the checked item. Thanks – New2coding Jan 26 '18 at 15:16
  • 1
    @New2Python If you have read about QActionGroup, this has the method [checkedAction](http://doc.qt.io/qt-5/qactiongroup.html#checkedAction), this returns the QAction that is selected. I recommend you read the docs before asking. :D – eyllanesc Jan 26 '18 at 15:32