Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

python - One QAction checkable at time in QMenu

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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_())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...