python - QObject之间的PyQt信号

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

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_()

最佳答案

对我有用-可能是您正在使用的Qt/PyQt版本,但您可以尝试以下几点:
使用正确的方法语法-so SIGNAL('request()')与SIGNAL('request')
使用新型信号语法
您使用的样式是旧样式的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_()

同样,我真的,真的不鼓励用这种方式构建代码……当你不需要的时候,你正在创建很多不必要的工作和对象的复制。