[PyKDE] subclassing widgets contained in a QtDesigner form

Jim Bublitz jbublitz at nwinternet.com
Fri Oct 25 03:56:01 BST 2002


On 24-Oct-02 Michael Ferraro wrote:
> I would like to sub-class a widget (QLabel for example) that I
> have placed (sized, colored, etc.) in QtDesigner in order to
> overide the mouseDoubleClickedEvent() .  
 
> I  realize I could modify the class generated by pyuic and
> change the "QLabel" to a "MyLabel" for each occurance
> but did not want to modify the files generated by pyuic
 
> I was wondering if there is some idomatic way of copying all the
> properties of a instance into a new one.without explicitly
> assigning them.

An instance's __dict__ (for example label.__dict__) contains all of
the class variables and their values (label.text is accessible as
label.__dict__["text"], or would be if it wasn't private in C++).
However with PyQt class instances you need to modify the values
stored in the underlying C++ object, so just replacing __dict__
won't do any good. The C++ values are the ones that appear on the
screen. In fact, since most Qt data members are private, they're not
directly accessible via Python under any circumstances (you'd need
to use label.setText ()/label.text () to write or read the value).

For the same reasons, playing around with something like copy
constructors probably won't work either.

There's a better solution at the end, however you could also try
(as a general method):

def myMouseDoubleClickEvent (s, e):   # s receives 'self',e is a
    <do stuff>                        # QMouseEvent
    QLabel.mouseDoubleClickEvent (s, e)
    <do more stuff>

label1.mouseDoubleClickEvent = myMouseDoubleClickEvent
label2.mouseDoubleClickEvent = myMouseDoubleClickEvent
etc.

Here's a crude equivalent done in the Python interpreter:

>>> class a:
...     def __init__ (self): pass
...     def output (self, s): print s
...
>>> def d(self0, s): print "Goodbye"
...
>>> c = a()
>>> c.output ("Hello")
Hello
>>> a.output = d
>>> c.output ("Hello")
Goodbye
>>>

also (using the original definition for class a):

>>> class e(a): pass
...
>>> c = e()
>>> c.output ("Hello")
Hello
>>> def f(self0, s): print "Goodbye";a.output (self0, s)
...
>>> e.output=f
>>> c.output ("Hello")
Goodbye
Hello
>>>

In Python, you don't need to subclass to overload a method :)

Since it's an event that you're working with, look at the Qt docs
for QObject::installEventHandler instead - you don't really need to
subclass to use that, and that's probably the best solution in this
case.


Jim




More information about the PyQt mailing list