PyQT - button.toggle() method not working PyQT - 按钮.toggle() 方法不起作用

2024-10-01 07:19:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个图形用户界面,在一个QButtonGroup容器中有两个单选按钮,这个容器本身在一个QGroupBox中(这个按钮组需要一个右键单击上下文菜单,由于QButtonGroup没有可视化表示,它似乎没有setContextMenuPolicy方法。)下面的代码片段应该更新互斥按钮的状态,以响应来自串行链接的传入数据:

elif widgetName in self.buttonBoxDict:
            buttonGroup = getattr(self.ui, self.buttonBoxDict[widgetName])
            checkedButton = buttonGroup.checkedButton()
            checkedButtonName = str(checkedButton.objectName())
            if value >= self.onValue and self.buttonDict[checkedButtonName][1] == self.offValue:
                checkedButton.toggle()
                assert(not checkedButton.isChecked())
                self.windowHandler.buttonChanged(self, self.onValue, cc)
            elif value < self.onValue and self.buttonDict[checkedButtonName][1] == self.onValue:
                checkedButton.toggle()
                self.windowHandler.buttonChanged(self, self.offValue, cc)

不幸的是,这不起作用,我知道最初这里选择的按钮是被选中的,但是GUI中按钮的状态从未改变,并且断言总是失败的,即使代码似乎执行得很好。你知道为什么会出错吗?在


Tags: and代码selfvalue状态按钮容器elif
2条回答

多亏了mandel的提醒,一个快速的解决方法就是将代码改成如下代码:

if value >= self.onValue and self.buttonDict[checkedButtonName][1] == self.offValue:
     for button in buttonGroup.buttons():
          if button != checkedButton:
               button.toggle()

您遇到的问题是基于这样一个事实:您使用的QButtonGroup被设置为独占的。如果您查看documentation,您将看到它声明了以下内容:

the user cannot uncheck the currently checked button by clicking on it; instead, another button in the group must be clicked

我不知道你的应用程序的逻辑,但如果你使用一个独占按钮组,你将需要设置一个差异按钮被检查,或不使用一个独占组,并强制检查自己。在

下面是您所看到的一个小例子:

import sys
from PyQt4 import QtGui

app = QtGui.QApplication(sys.argv)
button1 = QtGui.QCheckBox('test 1')
group = QtGui.QButtonGroup()
group.setExclusive(True)
group.addButton(button1)
print button1.isChecked()
button1.toggle()
print button1.isChecked()
button1.toggle()
print button1.isChecked()
# toggle seems not to work, add a second button
button2 =  QtGui.QCheckBox('test 2')
group.addButton(button2)
print button2.isChecked()
button2.toggle()
print button1.isChecked()
print button2.isChecked()

相关问题 更多 >