QObjects之间的PyQt信号

时间:2012-09-05 07:01:10

标签: python pyqt signals slot

我正在尝试在PyQt中创建视图和控制器,其中视图在单击按钮时发出自定义信号,并且控制器的一个方法连接到发出的信号。但是,它不起作用。单击按钮时不调用响应方法。知道我做错了吗?

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import QPushButton, QVBoxLayout, QDialog, QApplication 

class TestView(QDialog):
    def __init__(self, parent=None):
        super(TestView, self).__init__(parent)
        self.button = QPushButton('Click')
        layout = QVBoxLayout()
        layout.addWidget(self.button)
        self.setLayout(layout)
        self.connect(self.button, SIGNAL('clicked()'), self.buttonClicked)

    def buttonClicked(self):
        self.emit(SIGNAL('request'))

class TestController(QObject):
    def __init__(self, view):
        self.view = view
        self.connect(self.view, SIGNAL('request'), self.respond)

    def respond(self):
        print 'respond'

app = QApplication(sys.argv)
dialog = TestView()
controller = TestController(dialog)
dialog.show()
app.exec_()

1 个答案:

答案 0 :(得分:3)

适合我 - 可能是你正在使用的Qt / PyQt的版本,但有几件事你可以尝试:

  1. 使用正确的方法语法 - 所以SIGNAL('request()')与SIGNAL('request')
  2. 使用新式信号语法
  3. 您使用的样式是旧式PyQt语法,建议使用新式信号/插槽定义:

    import sys
    from PyQt4.QtCore import QObject, pyqtSignal  # really shouldn't import * here...QtCore library is quite large
    from PyQt4.QtGui import QPushButton, QVBoxLayout, QDialog, QApplication 
    
    class TestView(QDialog):
        request = pyqtSignal()
    
        def __init__(self, parent=None):
            super(TestView, self).__init__(parent)
            self.button = QPushButton('Click')
            layout = QVBoxLayout()
            layout.addWidget(self.button)
            self.setLayout(layout)
            self.button.clicked.connect(self.buttonClicked)
    
        def buttonClicked(self):
            self.request.emit()
    
    class TestController(QObject):
        def __init__(self, view):
            super(QObject, self).__init__()
            self.view = view
            self.view.request.connect(self.respond)
    
        def respond(self):
    
            print 'respond'
    
    app = QApplication(sys.argv)
    dialog = TestView()
    controller = TestController(dialog)
    dialog.show()
    app.exec_()
    

    再说一遍,我真的,真的不鼓励用这种方式构建代码......当你不需要的时候,你正在创造许多不必要的工作和重复的对象。