如何让我的qmenu可以检查?
from PyQt4 import QtGui
app = QtGui.QApplication([])
menu = QtGui.QMenu()
menu.addAction('50%')
menu.addAction('100%')
menu.addAction('200%')
menu.addAction('400%')
menu.show()
app.exec_()
答案 0 :(得分:27)
from PyQt4 import QtGui
app = QtGui.QApplication([])
w = QtGui.QMainWindow()
menu = QtGui.QMenu("menu", w)
menu.addAction(QtGui.QAction('50%', menu, checkable=True))
menu.addAction(QtGui.QAction('100%', menu, checkable=True))
menu.addAction(QtGui.QAction('200%', menu, checkable=True))
menu.addAction(QtGui.QAction('300%', menu, checkable=True))
menu.addAction(QtGui.QAction('400%', menu, checkable=True))
w.menuBar().addMenu(menu)
w.show()
app.exec_()
或使用单选按钮:
from PyQt4 import QtGui
app = QtGui.QApplication([])
w = QtGui.QMainWindow()
menu = QtGui.QMenu("menu", w)
ag = QtGui.QActionGroup(w, exclusive=True)
a = ag.addAction(QtGui.QAction('50%', w, checkable=True))
menu.addAction(a)
a = ag.addAction(QtGui.QAction('100%', w, checkable=True))
menu.addAction(a)
a = ag.addAction(QtGui.QAction('200%', w, checkable=True))
menu.addAction(a)
a = ag.addAction(QtGui.QAction('300%', w, checkable=True))
menu.addAction(a)
a = ag.addAction(QtGui.QAction('400%', w, checkable=True))
menu.addAction(a)
w.menuBar().addMenu(menu)
w.show()
app.exec_()
答案 1 :(得分:2)
我建议在紧凑的第一个解决方案中添加几行来显示按钮的实际用途:
from PyQt4 import QtGui, QtCore
def isChecked():
""" Prints selected menu labels. """
[print(action.text()) for action in menu.actions() if action.isChecked()]
app = QtGui.QApplication([])
w = QtGui.QMainWindow()
menu = QtGui.QMenu("menu", w)
menu.addAction(QtGui.QAction('50%', menu, checkable=True))
menu.addAction(QtGui.QAction('100%', menu, checkable=True))
menu.addAction(QtGui.QAction('200%', menu, checkable=True))
menu.addAction(QtGui.QAction('400%', menu, checkable=True))
menu.triggered.connect(isChecked)
w.menuBar().addMenu(menu)
w.show()
app.exec_()
答案 2 :(得分:0)
带有 PyQt5
子菜单的示例from PyQt5.QtWidgets import (
QMenu,
QAction,
)
menu = QMenu()
color_menu = QMenu('Player color')
white_color = QAction('White', checkable=True)
black_color = QAction('Black', checkable=True)
color_menu.addAction(white_color)
color_menu.addAction(black_color)
play_action = QAction('Start game')
menu.addAction(play_action)
menu.addMenu(color_menu)