One QAction checkable at time in QMenu

后端 未结 1 759
青春惊慌失措
青春惊慌失措 2020-12-11 13:19

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

相关标签:
1条回答
  • 2020-12-11 14:02

    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_())
    
    0 讨论(0)
提交回复
热议问题