如何在PyQt中连接不同对象的自定义信号?

时间:2014-04-17 14:14:34

标签: python qt pyqt

我不确定如何在两个不同的班级之间传递信号。我想要classA按钮自定义信号来显示classB按钮! 的 (self.butt2.setVisible(真)) 守则如下:

from PyQt4 import QtGui,QtCore
import sys
class A(QtGui.QWidget):
    customSignal = QtCore.pyqtSignal(str)
    def __init__(self,parent=None):
        super(A,self).__init__(parent)

        self.applyButton = QtGui.QPushButton('Apply')

        mLayout = QtGui.QHBoxLayout()
        mLayout.addWidget(self.applyButton)
        self.setLayout(mLayout)

        self.applyButton.clicked.connect(self.emitSignal)

        self.customSignal.connect(self.printStr)
    def emitSignal(self):
        self.customSignal.emit('classA')
    def printStr(self):
        print 'this is class A'

class B(QtGui.QWidget):
    def __init__(self,parent=None):
        super(B,self).__init__(parent)

        self.butt1 = QtGui.QPushButton('abc')
        self.butt2 = QtGui.QPushButton('def')

        self.butt2.setVisible(False)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addWidget(self.butt1)
        mainLayout.addWidget(self.butt2)

        self.setLayout(mainLayout)
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    a = A()   
    a.show()  

    b = B()
    b.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

假设您希望A类按钮切换B类按钮的可见性:

a.customSignal.connect(lambda: b.setVisible(not b.isVisible()))