Overloading virtual method of widget without inheriting (PyQt)

David Boddie dboddie at trolltech.com
Tue May 27 12:02:50 EDT 2008


On Mon May 26 17:37:04 CEST 2008, Alex Gusarov wrote:

> Hello, I have strong .NET background with C# and want to do some familiar
> things from it with Python, but don't know how. For example, I created form
> in qt designer with QCalendarWidget, translated it into Python module and
> want to overload virtual method paintCell of QCalendarWidget. In C# I can
> write following (abstract) code:
> 
> this.calendar.PaintCell += new PaintEventHandler(myPaintCellHandler);
> 
> void myPaintCellHandler(object sender, PaintEventArgs e) {
>     // some work here
> }

Right. I vaguely remember someone showing something like this at EuroPython
a couple of years ago. I believe that this approach is actually registering
an event handler (or callback) to handle a certain type of event.

> I can't find how I can do similar thing in Python without inheriting
> QCalendarWidget and overloading this method in inherited class (it's long
> and I must create additional class).

Just out of interest, given that you have to put the event handler somewhere,
why is it a problem to derive a new class and reimplement paintCell()?

It really isn't that much code:

  class MyCalendarWidget(QCalendarWidget):
  
      def paintCell(self, painter, rect, date):
          # some work here

> So, I need to run my code whenever paintCell is called by Qt internals and
> I have no enough experience with Python for it. Please, give me some
> advice, I know Python must be good enough to do such things.

The principal mechanism for doing this is via inheritance. You can do things
with event filters, but it's more complex and almost like working against the
design of the library to do so.

I have a feeling that the form produced by Qt Designer, once converted to
code, contains references to QCalendarWidget where you really want to use a
customized calendar widget. If so, you should "promote" the calendar widget
in Qt Designer to use your widget instead, and make sure you import the
module that supplies it in your application.

If you need more information about this, just ask.

David
-- 
David Boddie
Lead Technical Writer, Trolltech ASA



More information about the Python-list mailing list