简体   繁体   中英

Different ways to connect Signal to Slot

The code below creates a QLineEdit and a QPushButton . Pushing the button updates lineedit with a current time. This functionality is achieved by connecting button's 'clicked' signal to lineedit's update method using button.clicked.connect(line.update) .

在此处输入图片说明

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)

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

line = LineEdit()
line.show()

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

button = PushButton()
button.show()

button.clicked.connect(line.update)

app.exec_()

Instead of using button.clicked.connect(line.update) we could use:

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

or

QtCore.QObject.connect(button, QtCore.SIGNAL('clicked()'), line, QtCore.SLOT("update()"))

Alternatively we could declare the button's customSignal and connect it to the function we need:

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

Again, instead of using:

button.customSignal.connect(line.update)

we could use:

QtCore.QObject.connect(button, QtCore.SIGNAL('customSignal()'), line, QtCore.SLOT("update()"))

Question: Are there any drawbacks of using one approach over another?

The SIGNAL/SLOT examples all use obsolete syntax. This syntax should only be used in the increasingly rare situations where very old versions of PyQt still need to be supported. This means versions prior to 4.5, when the new-style signal and slot syntax was introduced. You should also be aware that the old-style syntax is no longer forwards-compatible, because PyQt5 does not support it at all anymore.

As for the example that overrides mouseEvent : it's completely redundant, so I can't imagine there's any generally applicable reason to prefer it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM