[PyQt] Simple example of subclassing

Phil Thompson phil at riverbankcomputing.com
Mon Nov 25 11:59:37 GMT 2013


On Mon, 25 Nov 2013 11:21:24 +0000, Brendan Donegan
<brendan.donegan at canonical.com> wrote:
> Hi,
> 
> Does anyone know any good resource for simple rules to follow around
> subclassing? I've found lots of specific examples through Googling, but
> nothing that explains in a basic way how to make it work.
> 
> Since I want to use this information to solve a specific problem too, I
> may as well throw it out there:
> 
> import sys
> from PyQt4.QtGui import QApplication, QGraphicsScene, QGraphicsView,
> QGraphicsTextItem
> 
> def TouchTextItem(QGraphicsTextItem):
> 
>     def __init__(self, text, parent=None):
>         QGraphicsTextItem.__init__(text, parent)
>         self.setAcceptTouchEvents(True)
> 
>     def sceneEvent(self, event):
>         print(event)
> 
> if __name__ == "__main__":
>     app = QApplication(sys.argv)
> 
>     scene = QGraphicsScene()
> 
>     touchTextItem = TouchTextItem("Click me!")
>     scene.addItem(touchTextItem)
> 
>     view = QGraphicsView(scene)
>     view.show()
> 
> I basically want to be able to handle and process the events the
> TouchTextItem recieves (specifically QTouchEvents). My debugging seems
> to indicate that the constructor never gets called but I can't figure
> out why - is it because the parameters to __init__ are wrong? Or maybe I
> need to implement some other functions to satisfy it. An answer to this
> specific problem would obviously be appreciated, but a general resource
> even more so.

You've defined TouchTextItem as a function, not a class.

Phil


More information about the PyQt mailing list