[PyQt] Simple example of subclassing

Brendan Donegan brendan.donegan at canonical.com
Mon Nov 25 11:21:24 GMT 2013


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.

Thanks,


More information about the PyQt mailing list