1

Problem

I have a class with a signal which is emitted during initialisation

from PySide.QtCore import *

class Example(QObject):
    signal = Signal()

    def __init__(self):
        super().__init__()
        self.signal.emit()

now i want to connect to the signal:

example = Example()
example.signal.connect(lambda: print('signal emitted'))

with this approach i will miss the signal, because the connection is made after the signal is already emitted

Solution?

my only idea to catch the signal is to create a second init method for the class like this:

from PySide.QtCore import *

class Example(QObject):
    signal = Signal()

    def __init__(self):
        super().__init__()

    def second_init(self):
        self.signal.emit()

and then connect this way:

example = Example()
example.signal.connect(lambda: print('signal emitted'))
example.second_init()

Questions

Is there a way to connect to the signal of the Example object right away without having to split the init method?

If thats not possible: Is the way i suggested the way to go or does a better way exist?

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
johnson
  • 3,729
  • 3
  • 31
  • 32

1 Answers1

1

You could pass the signal handler to the constructor:

from PySide.QtCore import *

class Example(QObject):
    signal = Signal()

    def __init__(self, handler=None):
        super().__init__()
        if handler is not None:
            self.signal.connect(handler)
        self.signal.emit()

example = Example(lambda: print('signal emitted'))
ekhumoro
  • 115,249
  • 20
  • 229
  • 336