python - QPushButton 切换连接似乎并未在开始时触发

标签 python pyqt pyqt4 qpushbutton

我正在连接一个 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/

相关文章:

python - PyQt4:使用 QVariantAnimation 在两个值之间设置动画

python - 如何在 PyQT5 中为 QPlainTextEdit(或任何其他组件)实现关键监听器

python - 如何为 Matplotlib 小部件(navBar/canvas)设置 PyQT4 样式表?

python - 如何将 storageaccount key 传递给 Linux VM?

python - 如何避免需要递归地使用正则表达式来删除字符串末尾的单词?

Python多索引: Changing second level of index names

python - PyQt:让小部件在 QDialog 中自动调整大小

python - 启用插件时pyqt4段错误(核心转储)

python - PyQt4:隐藏小部件并调整窗口大小

python - 像使用不同索引表的字符串一样解码 base64