当信号没有找到它的插槽时
Posted
技术标签:
【中文标题】当信号没有找到它的插槽时【英文标题】:When Signal Does Not Find its Slot 【发布时间】:2016-02-18 03:46:15 【问题描述】:单击按钮会使进程崩溃。有什么问题?
from PySide import QtCore, QtGui
class button(QtGui.QPushButton):
def __init__(self, parent=None):
super(button, self).__init__(parent)
self.clicked.connect(self.click)
self.show()
def click(self):
self.emit(QtCore.SIGNAL('customSignal'), 'String Argument')
btn = button()
class label(QtGui.QLabel):
def __init__(self, parent=None):
super(label, self).__init__(parent)
self.connect(btn, QtCore.SIGNAL('customSignal'), self.Function)
self.show()
@QtCore.Slot(str)
def Function(self, arg=None):
print 'Function arg: %r'%arg
lbl = label()
【问题讨论】:
【参考方案1】:不需要@QtCore.Slot
装饰器:
from PyQt4 import QtCore, QtGui
import sys
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
class button(QtGui.QPushButton):
def __init__(self, parent=None):
super(button, self).__init__(parent)
self.clicked.connect(self.click)
self.show()
def click(self):
self.emit(QtCore.SIGNAL('customSignal'), 'String Argument')
btn = button()
class label(QtGui.QLabel):
def __init__(self, parent=None):
super(label, self).__init__(parent)
self.connect(btn, QtCore.SIGNAL('customSignal'), self.method)
self.show()
def method(self, arg=None):
print 'method arg: %r'%arg
lbl = label()
sys.exit(app.exec_())
===================
from PySide import QtCore, QtGui
def function(arg=None):
print 'function arg: %r'%arg
class button(QtGui.QPushButton):
def __init__(self, parent=None):
super(button, self).__init__(parent)
self.clicked.connect(self.click)
self.show()
def click(self):
self.emit(QtCore.SIGNAL('customSignal'), 'String Argument')
btn = button()
class label(QtGui.QLabel):
def __init__(self, parent=None):
super(label, self).__init__(parent)
self.connect(btn, QtCore.SIGNAL('customSignal'), function)
self.show()
lbl = label()
====
from PyQt4 import QtCore, QtGui
import datetime
def getDatetime():
return '%s'%datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
class CustomEvent(QtCore.QEvent):
_type = QtCore.QEvent.registerEventType()
def __init__(self, name=None):
QtCore.QEvent.__init__(self, CustomEvent._type)
class label(QtGui.QLabel):
def __init__(self, parent=None):
super(label, self).__init__(parent)
def customEvent(self, event):
print '....customEvent %s if event.type(): %s == CustomEvent._type: %s'%(event, event.type(), CustomEvent._type)
if event.type() == CustomEvent._type:
self.setText(getDatetime() )
class button(QtGui.QPushButton):
def __init__(self, parent=None):
super(button, self).__init__(parent)
self.clicked.connect(self.onClick)
self.show()
def onClick(self):
event = CustomEvent(name = 'Event Name')
QtCore.QCoreApplication.postEvent(lbl, event)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
btn = button()
btn.show()
lbl = label()
lbl.show()
sys.exit(app.exec_())
【讨论】:
以上是关于当信号没有找到它的插槽时的主要内容,如果未能解决你的问题,请参考以下文章