busfault busfault - 6 months ago 25
Python Question

Can a QtCore Signal be set to the current class?

I am attempting to use a

QtCore.Signal
to send a new instance of a class to the object's parent.
What I am attempting to do is as follows, but fails with:


NameError: name 'myClass' is not defined



class myClass(QtGui.QMainWindow):
mySignal = QtCore.Signal(myClass)
def __init__(self, parent=None):
super(myClass, self).__init__(parent)

def create_new_self(self):
newSelf = myClass(self.parent())
self.mySignal.emit(newSelf)

class myParentClass(QtGui.QMainWindow):
def __init__(self, parent=None):
super(myParentClass, self).__init__(parent)
myNewClass = myClass(self)
myNewClass.mySignal.connect(self.handle_my_signal)

@QtCore.Slot(myClass)
def handle_my_signal(self, newMyClass):
newMyClass.mySignal.connect(self.handle_my_signal)
self.listOfClasses.append(newMyClass)


By Changing the line:

mySignal = QtCore.Signal(myClass)


to

mySignal = QtCore.Signal(QtGui.QMainWindow)


seems to fix the error, but I am not sure if that is the correct way to do something like this, other than it probably isn't the best way to do what I am doing.

Answer

The typical way to do this would be to define the signal as

mySignal = QtCore.Signal(object)

since you wish to emit an instance of a class.

EDIT: If you wish to work around the circular dependency, you can place your signal in a wrapper class. E.g.

class myClass(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(myClass, self).__init__(parent)
        # Note: argument of "self" is to parent the object
        self.signalwrapper = MyWrapper(self)

    def create_new_self(self):
        newSelf = myClass(self.parent())
        self.signalwrapper.mySignal.emit(newSelf)

class MyWrapper(QtCore.QObject):
    mySignal = QtCore.Signal(myClass)
Comments