Issue trying to use a class's name in it's

2019-07-31 01:52发布

问题:

I'm writing an app in Python and PyQt right now, and I've having a bit of an issue. This problem doesn't require an knowledge of PyQt itself, just that of static variables in python. I'm tyring to add some signals to a class, which will emit the instance of the class when the signal is tripped.

What I have is something like this:

class Foo(QObject):
    # ...
    # Signals
    updated = pyqtSignal(Foo)
    moved = pyqtSignal(Foo)
    # ...

Python is giving me the error:

NameError: name 'Foo' is not defined

IIRC, this has to do something with when the class Foo is bound to the globals. I also can't use self here either. Any help on how to fix this issue would be appreciated.

回答1:

The problem is that the statement updated = pyqtSignal(Foo) is evaluated while Foo is being constructed, so Foo doesn't exist when that statement is evaluated.. In the general case, you'd have to move it outside the class definition, although there may be some pyqt magic (e.g. using QObject rather than Foo as described in the other answer):

class Foo(...):
   ...

Foo.updated = pyqtSignal(Foo)


回答2:

Sound like this signal pass own class variable. From reference this pyqt signal. It possibly to use QObject. (not Foo but subclass is same)

Or, if your want to pass anything object, I think your can use object;

class Foo(QObject):
    updated = pyqtSignal(object)
    moved = pyqtSignal(object)

And your can specified what class should be emit it in pyqt connect signal.