views:

189

answers:

1
+4  Q: 

PyQt subclassing

The usual way to use Qt widgets from Python seems to be to subclass them.

Qt widget classes have a great many methods, so inevitably I'm going to end up adding a method to the subclass, with the same name as one inherited from the Qt widget. In Python, all methods are virtual, so what I'm concerned about is that some Qt code might end up calling my method instead of the expected Qt one - in the worst-case scenario, breaking some edge case that doesn't easily show up in testing.

On the other hand, maybe all the PyQt methods are just wrappers for C++ code, which would of course be unaffected by anything I do in terms of Python subclassing.

Anyone know offhand which is the case?

+2  A: 

If the underlaying C++ methods are virtual, your Python methods that override them will be called any time C++ code calls them. If they are just regular methods, any C++ code will call the original C++ methods by default (Python code will call the Python methods though, because it sees the Python object and all methods are "virtual" there).

Lukáš Lalinský
Ah, PyQt goes that far? Of course that's good news in the case where you do want to override a Qt method, but bad news in the case where you don't. Would it be better, then, to delegate instead of subclass?
rwallace
If you don't want to override, give it a different name. Btw, what do you mean by delegate?
Marcus Lindblom
Why not just go by PEP 8 and name all your methods with lowercase/underscores? Qt uses camelCase so you won't have any clashes... except possibly for one-word method names...
Jesse Aldridge
I am naming all my methods with lowercase, but there are a number of one-word method names, enough that I'm not going to remember them all, leaving aside the possibility of more being added in future versions. By delegate I mean instead of having your class inherit a widget, have it contain a self.widget attribute.
rwallace
If you want it to act as a widget, you have to subclass the QWidget, so you have the same problem. There is really no way around it. Really, just give you methods different names, make them more specific, etc.
Lukáš Lalinský
I suppose you could adopt a convention of appending an underscore to your method names or something like that. Although I've found that debugging this sort of name conflict isn't too hard once you know to watch out for it.
Jesse Aldridge
Yeah, the convention I ended up with is to begin all my method names (in classes that subclass Qt stuff, where I am not trying to override an inherited method) with a capital letter. That way I don't have to think about the issue anymore.
rwallace