Understanding pyqtProperty in PyQt4
I wrote the following little script to understand properties. One thing which I cannot understand is, that the metaObject()
of my class A
contains a property with the name conf_name
now. How did it get that information? In my class it is only used once as name for the target variable of the call to set the property. How can this be realized? Can it also be realized with plain Python, i.e. without the C API?
#!/usr/bin/python
from PyQt4.QtCore import QObject, pyqtProperty
from PyQt4.QtGui import QApplication
class A( QObject ):
def __init__( self, parent = None ):
QObject.__init__( self )
self.开发者_Python百科_name = ""
def getName( self ):
return self._name
def setName( self, value ):
self._name = value
conf_name = pyqtProperty( "QString", getName, setName )
a = QApplication([])
ai = A()
for i in range( ai.metaObject().propertyCount() ):
print ai.metaObject().property( i ).name()
if this is not supposed to be a property of your object class, it belongs in that classes __init__
function. What you have there is a class property, which will be inherited by all objects of that object type of subclassing it.
This can actually be quite useful. For instance:
for PyQt4.QtCore import QThread
class My_Thread(QThread):
all_instances = []
def __del__(self, *args, **kwargs):
all_instances.remove(self)
QThread.__del__(self, *args, **kwargs)
def __init__(self, *args, **kwargs):
QThread.__init__(self, *args, **kwargs)
my_locally_scoped_variable = None
self.all_instances.append(self)
This class creates a subclass of QThread, which matches its exact interface, except if I create thread = My_Thread(blahblahblah)
, I can get a list of all the other threads of this type, and any subclassing it by querying thread.all_instances
, or even thread.all_instances[-1].all_instances
. You mush however handle object deletion otherwise a reference will always exist to each item of your class, and therefore never be garbage-collected.
Also notice that my_locally_scoped_variable
only exists within the scope of __init__
and does not create a property.
精彩评论