简体   繁体   中英

Implementing checkable buttons in Pyqt5 file menu to act similarly to radio buttons

I have created a file menu in PyQt5 with a "File" option with two checkable buttons (button1, button2). Unfortunately, I have not found a way to implement radio buttons into the file menu so I assume at the moment it is not possible. Instead, I would like to make these two checkable buttons act like radio buttons - this means that if one is checked the other becomes unchecked. Only one can be checked at a given time.

I have attempted to do it this way (which I find the most logical and straightforward), but it does not work:

def fileMenu(self):
    if self.button1.isChecked() == True:
    self.button2.setChecked(False)

If I check button2 and then check button1, button2 does not uncheck. Is there any other way to do this or any error in my code preventing it from working? Or... ideally is there any way to implement radio buttons into the file menu?

You can accomplish this using a QActionGroup. You would have to group all those buttons together under an action group. It will not work otherwise. The documentation can be found here.


w is your QtMainWindow, ag is defining the QActionGroup, and menu is the name of your menu.

ag = QtGui.QActionGroup(w, exclusive=True)
a = ag.addAction(action_a)
menu.addAction(a)
b = ag.addAction(action_b)
menu.addAction(b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM