pawel
pawel

Reputation: 1079

pySide signal and slots too much code?

I recently started to use new pySide signal and slots and I found that I need a lot of code to handle them. I guess I do something wrong and hope that someone have a better way of doing it.

#first I need to declare it at the class level
class UI(QtGui.QMainWindow):
    my_signal = QtCore.Signal(str, str)

# next I need to connect it to something in the UI
self.my_signal.connect(self._mySignalHandler)

# then I need the actual handler that does the work:
@QtCore.Slot(str, str)
def _mySignalHandler(self, a, b):
    pass

# and finally I needs an accessor method for it to use it from the outside the UI class:
def mySignalAccessor(self, a, b):
    self.my_signal.emit(a, b)

this is a lot of code to do a simple thing. I end up having two methods and a variable all called similarly - really good way to get totally lost in bugs. Do you have a better way do do that?

Upvotes: 0

Views: 652

Answers (1)

ekhumoro
ekhumoro

Reputation: 120798

It's only three lines of code: definition, connection, handler. The accessor is redundant (just give the signal a good, descriptive name and use it like any other built-in signal).

You can probably get rid of the slot decorator, which is not normally required (a signal can be connected to any Python callable, it doesn't have to be a slot).

As for the naming: just pick a format, and stick with it throughout all your projects. For example:

    dataReceived = QtCore.Signal(object)

    self.dataReceived.connect(self.handleDataReceived)

    def handleDataReceived(self, data):

Boiler-plate code like this can easily be inserted via a template, if your editor has support for that kind of thing.

PS:

In PyQt, there is support for Connecting Slots By Name - I've never used it myself, and I don't know whether it's also supported in PySide, but you might find it useful.

Upvotes: 1

Related Questions