在QMenu中可以检查一次QAction

时间:2018-01-25 15:58:01

标签: python python-3.x pyqt pyqt5 qmenu

我试图从QMenu做出我的选择,以便能够检查一次只能选择一个,默认情况下设置第一个项目(这实际上有效)。

以下是我的代码片段:

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)

有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:1)

可能的选择是使用QActionGroup并激活exclusive属性

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_())
相关问题