以下代碼創建一個QLineEdit
和QPushButton
。按下按鈕更新lineedit與當前時間。通過將按鈕的「單擊」信號連接到lineedit的update
方法,使用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_()
而不是使用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()"))
或者我們可以decla重新按鈕的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。新的語法支持舊的語法。前進...前進,永不回頭。 –