本文介紹了在 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!