How can i make my qmenu checkable?
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_()
like this:
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_()
or witht radio buttons:
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_()
I suggest adding a few lines to the compact first solution to show the actual use of the buttons:
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_()
Example for with submenu for 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)
QMenu
checkable or actions? AFAIK,QMenu
can't be checkable. – Avaris