Python 将信号连接到插槽的不同方式

Python 将信号连接到插槽的不同方式,python,qt,pyqt,signals-slots,Python,Qt,Pyqt,Signals Slots,下面的代码创建了一个QLineEdit和一个QPushButton。按此按钮可使用当前时间更新lineedit。此功能是通过使用button.clicked.connect(line.update)将按钮的“clicked”信号连接到lineedit的update方法来实现的 不要使用按钮。单击。连接(line.update)我们可以使用: QtCore.QObject.connect(按钮,QtCore.SIGNAL('clicked()'),line.update) 或 QtCore.QO

下面的代码创建了一个
QLineEdit
和一个
QPushButton
。按此按钮可使用当前时间更新lineedit。此功能是通过使用
button.clicked.connect(line.update)
将按钮的“clicked”信号连接到lineedit的
update
方法来实现的

不要使用
按钮。单击。连接(line.update)
我们可以使用:

QtCore.QObject.connect(按钮,QtCore.SIGNAL('clicked()'),line.update)

QtCore.QObject.connect(按钮、QtCore.SIGNAL('clicked()')、行、QtCore.SLOT(“update()”)

或者,我们可以声明按钮的
customSignal
,并将其连接到我们需要的功能:

import datetime
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])


class LineEdit(QtGui.QLineEdit):
    def __init__(self, parent=None):
        super(LineEdit, self).__init__(parent=parent)

    @QtCore.pyqtSlot()
    def update(self, some=None):
        self.setText(str(datetime.datetime.now()))

line = LineEdit()
line.show()


class PushButton(QtGui.QPushButton):
    customSignal = QtCore.pyqtSignal()
    def __init__(self, parent=None):
        super(PushButton, self).__init__(parent=parent)

    def mousePressEvent(self, event):
        super(PushButton, self).mousePressEvent(event)
        self.customSignal.emit()
        event.ignore()


button = PushButton()
button.show()

button.customSignal.connect(line.update)

app.exec_()
同样,不要使用:

按钮。自定义信号。连接(线路。更新)

我们可以使用:

QtCore.QObject.connect(按钮、QtCore.SIGNAL('customSignal()')、行、QtCore.SLOT(“update()”)


问题:使用一种方法比使用另一种方法有什么缺点吗?

信号/插槽的
示例都使用过时的语法。这种语法只应在越来越少的情况下使用,在这种情况下仍然需要支持非常旧的PyQt版本。这意味着引入时4.5之前的版本。您还应该知道,旧式语法不再是向前兼容的,因为PyQt5不再支持它


至于覆盖
mouseEvent
的示例:它是完全冗余的,因此我无法想象有任何一般的合适的理由来选择它。

谢谢您的消息!为什么为按钮实现
customSignal
并覆盖其
mouseEvent
的示例被认为是冗余的?@spootnx。我假设您的意思是它相当于
单击的
信号(与其他示例一样)。在这种情况下,它是多余的,因为它是一种实现内置信号已经提供的东西的过于复杂的方式。当然,正如您所写的,代码并不是真正等价的,因为按下鼠标与单击鼠标是不同的。因此,自定义信号示例可以被认为是冗余的和有缺陷的。(PS:您不想使用内置信号有什么具体原因吗?)旧语法冗长、难看且以字符串为中心。新语法简洁、简洁、pythonic。新语法支持旧语法所做的一切。前进。。。向前走,永不回头。
import datetime
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])


class LineEdit(QtGui.QLineEdit):
    def __init__(self, parent=None):
        super(LineEdit, self).__init__(parent=parent)

    @QtCore.pyqtSlot()
    def update(self, some=None):
        self.setText(str(datetime.datetime.now()))

line = LineEdit()
line.show()


class PushButton(QtGui.QPushButton):
    customSignal = QtCore.pyqtSignal()
    def __init__(self, parent=None):
        super(PushButton, self).__init__(parent=parent)

    def mousePressEvent(self, event):
        super(PushButton, self).mousePressEvent(event)
        self.customSignal.emit()
        event.ignore()


button = PushButton()
button.show()

button.customSignal.connect(line.update)

app.exec_()