简体   繁体   English

在Pyqt5文件菜单中实现可检查按钮以类似于单选按钮

[英]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). 我在PyQt5中创建了一个带有“文件”选项的文件菜单,该菜单带有两个可检查的按钮(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. 如果我先检查button2,然后再检查button1,则button2不会取消选中。 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. 您可以使用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. 该文档可在此处找到

Here is an example of implementing a QActionGroup with two radio buttons: 这是使用两个单选按钮实现QActionGroup的示例:
w is your QtMainWindow, ag is defining the QActionGroup, and menu is the name of your menu. w是您的QtMainWindow, ag是定义QActionGroup,而menumenu的名称。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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