我正在连接一个 QPushButton,它将在其中隐藏/显示框架内的小部件。
我使用 .ui
方法加载/创建了我的 GUI。
对于这个 QPushButton,我设置并检查了属性 setChecked
。
class MyWindow(QtGui.QWidget):
def __init__(self):
...
# self.informationVisBtn, `setChecked` and `setCheckable` field is checked in the .ui file
self.informationVisBtn.toggled.connect(self.setInfoVis)
def setInfoVis(self):
self.toggleVisibility(
self.informationVisBtn.isChecked()
)
def toggleVisibility(self, value):
if value:
self.uiInformationFrame.show()
self.informationVisBtn.setText("-")
else:
self.uiInformationFrame.hide()
self.informationVisBtn.setText("+")
在第一次尝试加载我的代码时,我注意到 informationVisBtn
在检查时显示了框架,但文本并未设置为 -
相反,它保留为我的 .ui 文件中设置的 +
。
除非在__init__()
中,如果我在设置连接之前添加setInfoVis()
,则只能正确填充文本。
使用toggled
不会触发开始时的状态吗?提前感谢您的回复。
最佳答案
当状态发生变化时会发出信号,并通知当时连接的插槽。当连接新插槽时,只有在连接后状态发生变化时才会收到通知,因此始终建议将状态更新为信号。另一方面,由于切换会传输状态信息,因此无需创建 setInfoVis() 方法。
class MyWindow(QtGui.QWidget):
def __init__(self):
super(MyWindow, self).__init__()
# ...
self.informationVisBtn.toggled.connect(self.toggleVisibility)
# update the state it has since the connection
# was made after the state change
self.toggleVisibility(
self.informationVisBtn.isChecked()
)
@QtCore.pyqtSlot(bool)
def toggleVisibility(self, value):
self.uiInformationFrame.setVisible(value)
self.informationVisBtn.setText("-" if value else "+")
关于python - QPushButton 切换连接似乎并未在开始时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53753039/