在 QMenu 中一次可检查一个 QAction

One QAction checkable at time in QMenu(在 QMenu 中一次可检查一个 QAction)

本文介绍了在 QMenu 中一次可检查一个 QAction的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使我从 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).

这是我的代码片段:

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)

有什么建议吗?谢谢!

推荐答案

一个可能的选择是使用 QActionGroup 并激活 专有属性

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

这篇关于在 QMenu 中一次可检查一个 QAction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 QMenu 中一次可检查一个 QAction

基础教程推荐