What is the correct method of handling events in PyQt 4?
I have seen examples like this:
self.connect(self.ui.add_button, QtCore.SIGNAL('clicked()'),self.printer)
And examples like this:
self.ui.add_button.clicked.connec开发者_StackOverflow中文版t(self.printer)
I'm just starting to learn Qt; which one should I focus on?
I think that the second example is only supported by some Qt versions (the newer ones), while the first it supported by older ones. But, both are correct.
AFAIK, the newer style doesn't work if there are overloaded signals, so
self.ui.add_button.clicked.connect(self.printer)
can't be used if there's also, say, a
clicked(float, float)
so you'd have to fall back to the older style. It's always good to know both.
I know this post is pretty old, but I just stumbled across it, maybe you will too and now this saves your day ;) ok... by the way, it's my first post here on SO, yey!
WARNING, i did not test this code, i just copied some snippets of code i wrote some time ago, so, there may be some error, but I hope it helps anyway
PyQt's new style signals briefly:
# notice that the signal declarations are at class level (not inside some method)
class MyClass(QObject): # must subclass QObject (or subclass)
# declaring signals
mySimpleSignal = pyqtSignal()
mySignalWithArguments = pyqtSignal(int, list)
myOverloadedSignal = ([int, object],[str,object])
def __init__(self, parent=None):
super(MyClass,self).__init__(parent=parent) # remember to init the super class
[...]
# methods
[...]
# connecting signals
def connectSignalsMethod(self):
# connecting simple signal
self.mySimpleSignal.connect(self.mySlot)
# connecting signal with arguments
self.mySignalWithArguments.connect(self.mySlotWithArguments)
# connecting overloaded signals
self.myOverloadedSignal[int, object].connect(self.mySlot1)
self.myOverloadedSignal[str, object].connect(self.mySLot2)
# same syntax for disconnect()
# emitting signals
def emitSignalsMethod(self):
# emitting simple signal
self.mySimpleSignal.emit()
# emitting signal with arguments
self.mySignalWithArguments.emit(123,['this','is','a','list'])
# emitting overloaded signal
myOverloadedSignal[str,object].emit('this is a string', myObject)
# my slots
@pyqtSlot()
def mySlot(self):
print('hey!')
@pyqtSlot(int, list)
def mySlotWithArguments(self, someNumber, someList):
print('got a number: %d and a list: %s' % (someNumber, someList))
@pyqtSlot(int, object)
def mySlot1(self, intArg, objectArg):
print('got an int and an object')
@pyqtSlot(str, object)
def mySlot2(self, str, object):
print('got a string and an object')
# an overloaded slot
@pyqtSignal(int)
@pyqtSignal(str)
def overloadedSlot(someArgument)
print('got something: %s' % someArgument)
otherwise, try this http://www.harshj.com/2010/05/06/pyqt-faq-custom-signals-jpeg-mouse-hovers-and-more/#custom
Edit: events and signals are not the same, what you see above is about signals
精彩评论