【问题标题】:PyQt signal between QObjectsQObjects之间的PyQt信号
【发布时间】:2017-06-24 11:33:13
【问题描述】:

我正在尝试在 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_()

【问题讨论】:

    标签: python pyqt signals slot


    【解决方案1】:

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

    1. 使用正确的方法语法 - 所以 SIGNAL('request()') 与 SIGNAL('request')
    2. 使用新型信号语法

    您使用的样式是旧式 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_()
    

    同样,我真的非常不鼓励以这种方式构建您的代码...当您不需要时,您会创建大量不必要的工作和对象重复。

    【讨论】:

    • 同时,我发现我应该在我的 TestController 的 init 中调用 QObject 的 init: QObject.__init__(self) 谢谢你的建议,Eric,非常感激。如果我理解正确,您会鼓励直接在 TestView 的 buttonClicked 方法中处理按钮单击?
    • 哎呀,是的,我错过了 - 这很可能导致问题......奇怪它在我的测试中起作用,它可能对我来说也应该失败。我以为你是问这个问题的同一个人,因为它几乎完全一样:stackoverflow.com/questions/12270327/…
    猜你喜欢
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 2018-09-23
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    相关资源
    最近更新 更多