【发布时间】:2016-09-06 07:41:01
【问题描述】:
下面的代码创建了一个QLineEdit 和一个QPushButton。按下按钮以当前时间更新 lineedit。此功能是通过使用 button.clicked.connect(line.update) 将按钮的 'clicked' 信号连接到 lineedit 的 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_()
我们可以使用 button.clicked.connect(line.update) 代替:
QtCore.QObject.connect(button, QtCore.SIGNAL('clicked()'), line.update)
或
QtCore.QObject.connect(button, QtCore.SIGNAL('clicked()'), line, 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_()
再次,而不是使用:
button.customSignal.connect(line.update)
我们可以使用:
QtCore.QObject.connect(button, QtCore.SIGNAL('customSignal()'), line, QtCore.SLOT("update()"))
问题:使用一种方法比另一种方法有什么缺点吗?
【问题讨论】:
-
旧语法冗长、丑陋且以字符串为中心。新的语法干净、简洁、pythonic。新语法支持旧语法所做的一切。往前走……往前走,永不回头。
标签: python qt pyqt signals-slots