Warning

This section contains snippets that were automatically translated from C++ to Python and may contain errors.

Tablet Example#

This example shows how to use a Wacom tablet in Qt applications.

../_images/tabletexample.png

When you use a tablet with Qt applications, QTabletEvents are generated. You need to reimplement the tabletEvent() event handler if you want to handle tablet events. Events are generated when the tool (stylus) used for drawing enters and leaves the proximity of the tablet (i.e., when it is closed but not pressed down on it), when the tool is pressed down and released from it, when the tool is moved across the tablet, and when one of the buttons on the tool is pressed or released.

The information available in QTabletEvent depends on the device used. This example can handle a tablet with up to three different drawing tools: a stylus, an airbrush, and an art pen. For any of these the event will contain the position of the tool, pressure on the tablet, button status, vertical tilt, and horizontal tilt (i.e, the angle between the device and the perpendicular of the tablet, if the tablet hardware can provide it). The airbrush has a finger wheel; the position of this is also available in the tablet event. The art pen provides rotation around the axis perpendicular to the tablet surface, so that it can be used for calligraphy.

In this example we implement a drawing program. You can use the stylus to draw on the tablet as you use a pencil on paper. When you draw with the airbrush you get a spray of virtual paint; the finger wheel is used to change the density of the spray. When you draw with the art pen, you get a line whose width and endpoint angle depend on the rotation of the pen. The pressure and tilt can also be assigned to change the alpha and saturation values of the color and the width of the stroke.

The example consists of the following:

  • The MainWindow class inherits QMainWindow , creates the menus, and connects their slots and signals.

  • The TabletCanvas class inherits QWidget and receives tablet events. It uses the events to paint onto an offscreen pixmap, and then renders it.

  • The TabletApplication class inherits QApplication . This class handles tablet proximity events.

  • The main() function creates a MainWindow and shows it as a top level window.

MainWindow Class Definition#

The MainWindow creates a TabletCanvas and sets it as its center widget.

class MainWindow(QMainWindow):

    Q_OBJECT
# public
    MainWindow(TabletCanvas canvas)
# private slots
    def setBrushColor():
    def setAlphaValuator(action):
    def setLineWidthValuator(action):
    def setSaturationValuator(action):
    def setEventCompression(compress):
    save = bool()
    def load():
    def clear():
    def about():
# private
    def createMenus():
    m_canvas = TabletCanvas()
    m_colorDialog = None

createMenus() sets up the menus with the actions. We have one QActionGroup for the actions that alter the alpha channel, color saturation and line width respectively. The action groups are connected to the setAlphaValuator(), setSaturationValuator(), and setLineWidthValuator() slots, which call functions in TabletCanvas.

MainWindow Class Implementation#

We start with a look at the constructor MainWindow():

def __init__(self, canvas):
    self.m_canvas = canvas

    createMenus()
    setWindowTitle(tr("Tablet Example"))
    setCentralWidget(m_canvas)
    QCoreApplication.setAttribute(Qt.AA_CompressHighFrequencyEvents)

In the constructor we call createMenus() to create all the actions and menus, and set the canvas as the center widget.

def createMenus(self):

    fileMenu = menuBar().addMenu(tr("File"))
    fileMenu->addAction(tr("&Open..."), QKeySequence::Open, self.load)
    fileMenu->addAction(tr("&Save As..."), QKeySequence::SaveAs, self.save)
    fileMenu->addAction(tr("&New"), QKeySequence::New, self.clear)
    fileMenu->addAction(tr("E&xit"), QKeySequence::Quit, self.close)
    brushMenu = menuBar().addMenu(tr("Brush"))
    brushMenu->addAction(tr("&Brush Color..."), tr("Ctrl+B"), self.setBrushColor)

At the beginning of createMenus() we populate the File menu. We use an overload of addAction() , introduced in Qt 5.6, to create a menu item with a shortcut (and optionally an icon), add it to its menu, and connect it to a slot, all with one line of code. We use QKeySequence to get the platform-specific standard key shortcuts for these common menu items.

We also populate the Brush menu. The command to change a brush does not normally have a standard shortcut, so we use tr() to enable translating the shortcut along with the language translation of the application.

Now we will look at the creation of one group of mutually-exclusive actions in a submenu of the Tablet menu, for selecting which property of each QTabletEvent will be used to vary the translucency (alpha channel) of the line being drawn or color being airbrushed.

alphaChannelMenu = tabletMenu.addMenu(tr("Alpha Channel"))
alphaChannelPressureAction = alphaChannelMenu.addAction(tr("Pressure"))
alphaChannelPressureAction.setData(TabletCanvas.PressureValuator)
alphaChannelPressureAction.setCheckable(True)
alphaChannelTangentialPressureAction = alphaChannelMenu.addAction(tr("Tangential Pressure"))
alphaChannelTangentialPressureAction.setData(TabletCanvas.TangentialPressureValuator)
alphaChannelTangentialPressureAction.setCheckable(True)
alphaChannelTangentialPressureAction.setChecked(True)
alphaChannelTiltAction = alphaChannelMenu.addAction(tr("Tilt"))
alphaChannelTiltAction.setData(TabletCanvas.TiltValuator)
alphaChannelTiltAction.setCheckable(True)
noAlphaChannelAction = alphaChannelMenu.addAction(tr("No Alpha Channel"))
noAlphaChannelAction.setData(TabletCanvas.NoValuator)
noAlphaChannelAction.setCheckable(True)
alphaChannelGroup = QActionGroup(self)
alphaChannelGroup.addAction(alphaChannelPressureAction)
alphaChannelGroup.addAction(alphaChannelTangentialPressureAction)
alphaChannelGroup.addAction(alphaChannelTiltAction)
alphaChannelGroup.addAction(noAlphaChannelAction)
alphaChannelGroup.triggered.connect(
        self.setAlphaValuator)

We want the user to be able to choose whether the drawing color’s alpha component should be modulated by the tablet pressure, tilt, or the position of the thumbwheel on the airbrush tool. We have one action for each choice, and an additional action to choose not to change the alpha, that is, to keep the color opaque. We make the actions checkable; the alphaChannelGroup will then ensure that only one of the actions are checked at any time. The triggered() signal is emitted from the group when an action is checked, so we connect that to MainWindow::setAlphaValuator(). It will need to know which property (valuator) of the QTabletEvent to pay attention to from now on, so we use the QAction::data property to pass this information along. (In order for this to be possible, the enum Valuator must be a registered metatype, so that it can be inserted into a QVariant. That is accomplished by the Q_ENUM declaration in tabletcanvas.h.)

Here is the implementation of setAlphaValuator():

def setAlphaValuator(self, action):

    m_canvas.setAlphaChannelValuator(TabletCanvas.Valuator(action.data()))

It simply needs to retrieve the Valuator enum from QAction::data(), and pass that to TabletCanvas::setAlphaChannelValuator(). If we were not using the data property, we would instead need to compare the QAction pointer itself, for example in a switch statement. But that would require keeping pointers to each QAction in class variables, for comparison purposes.

Here is the implementation of setBrushColor():

def setBrushColor(self):

    if not m_colorDialog:
        m_colorDialog = QColorDialog(self)
        m_colorDialog.setModal(False)
        m_colorDialog.setCurrentColor(m_canvas.color())
        m_colorDialog.colorSelected.connect(m_canvas.setColor)

    m_colorDialog.setVisible(True)

We do lazy initialization of a QColorDialog the first time the user chooses Brush color… from the menu or via the action shortcut. While the dialog is open, each time the user chooses a different color, TabletCanvas::setColor() will be called to change the drawing color. Because it is a non-modal dialog, the user is free to leave the color dialog open, so as to be able to conveniently and frequently change colors, or close it and re-open it later.

Here is the implementation of save():

def save(self):

    path = QDir.currentPath() + "/untitled.png"()
    fileName = QFileDialog.getSaveFileName(self, tr("Save Picture"),()
                             path)
    success = m_canvas.saveImage(fileName)
    if not success:
        QMessageBox.information(self, "Error Saving Picture",
                                 "Could not save the image")
    return success

We use the QFileDialog to let the user select a file to save the drawing, and then call TabletCanvas::saveImage() to actually write it to the file.

Here is the implementation of load():

def load(self):

    fileName = QFileDialog.getOpenFileName(self, tr("Open Picture"),()
                                                    QDir.currentPath())
    if not m_canvas.loadImage(fileName):
        QMessageBox.information(self, "Error Opening Picture",
                                 "Could not open picture")

We let the user select the image file to be opened with a QFileDialog ; we then ask the canvas to load the image with loadImage().

Here is the implementation of about():

def about(self):

    QMessageBox.about(self, tr("About Tablet Example"),
                       tr("This example shows how to use a graphics drawing tablet in Qt."))

We show a message box with a short description of the example.

TabletCanvas Class Definition#

The TabletCanvas class provides a surface on which the user can draw with a tablet.

class TabletCanvas(QWidget):

    Q_OBJECT
# public
    Valuator = { PressureValuator, TangentialPressureValuator,
                    TiltValuator, VTiltValuator, HTiltValuator, NoValuator }
    Q_ENUM(Valuator)
    TabletCanvas()
    saveImage = bool(QString file)
    loadImage = bool(QString file)
    def clear():
    def setAlphaChannelValuator(type):
        { m_alphaChannelValuator = type; }
    def setColorSaturationValuator(type):
        { m_colorSaturationValuator = type; }
    def setLineWidthType(type):
        { m_lineWidthValuator = type; }
    def setColor(c):
        { if (c.isValid()) m_color = c; }
    def color():
        { return m_color; }
    def setTabletDevice(event):
        { updateCursor(event); }
# protected
    def tabletEvent(event):
    def paintEvent(event):
    def resizeEvent(event):
# private
    def initPixmap():
    def paintPixmap(painter, event):
    Qt.BrushStyle brushPattern(qreal value)
    pressureToWidth = qreal(qreal pressure)
    def updateBrush(event):
    def updateCursor(event):
    m_alphaChannelValuator = TangentialPressureValuator()
    m_colorSaturationValuator = NoValuator()
    m_lineWidthValuator = PressureValuator()
    m_color = Qt.red()
    m_pixmap = QPixmap()
    m_brush = QBrush()
    m_pen = QPen()
    m_deviceDown = False
    class Point():
        pos = QPointF()
        pressure = 0
        rotation = 0
    } lastPoint

The canvas can change the alpha channel, color saturation, and line width of the stroke. We have an enum listing the QTabletEvent properties with which it is possible to modulate them. We keep a private variable for each: m_alphaChannelValuator, m_colorSaturationValuator and m_lineWidthValuator, and we provide accessor functions for them.

We draw on a QPixmap with m_pen and m_brush using m_color. Each time a QTabletEvent is received, the stroke is drawn from lastPoint to the point given in the current QTabletEvent, and then the position and rotation are saved in lastPoint for next time. The saveImage() and loadImage() functions save and load the QPixmap to disk. The pixmap is drawn on the widget in paintEvent().

The interpretation of events from the tablet is done in tabletEvent(), and paintPixmap(), updateBrush(), and updateCursor() are helper functions used by tabletEvent().

TabletCanvas Class Implementation#

We start with a look at the constructor:

def __init__(self):
    super().__init__(None)
    self.m_brush = m_color
    , m_pen(m_brush, 1.0, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)

    resize(500, 500)
    setAutoFillBackground(True)
    setAttribute(Qt.WA_TabletTracking)

In the constructor we initialize most of our class variables.

Here is the implementation of saveImage():

def saveImage(self, QString file):

    return m_pixmap.save(file)

QPixmap implements functionality to save itself to disk, so we simply call save().

Here is the implementation of loadImage():

def loadImage(self, QString file):

    success = m_pixmap.load(file)
    if success:
        update()
        return True

    return False

We simply call load(), which loads the image from file.

Here is the implementation of tabletEvent():

def tabletEvent(self, event):

    switch (event.type()) {
        elif index == QEvent.TabletPress:
            if not m_deviceDown:
                m_deviceDown = True
                lastPoint.pos = event.position()
                lastPoint.pressure = event.pressure()
                lastPoint.rotation = event.rotation()

            break
        elif index == QEvent.TabletMove:
#ifndef Q_OS_IOS
            if event.pointingDevice() and event.pointingDevice().capabilities().testFlag(QPointingDevice.Capability.Rotation):
                updateCursor(event)
#endif
            if m_deviceDown:
                updateBrush(event)
                painter = QPainter(m_pixmap)
                paintPixmap(painter, event)
                lastPoint.pos = event.position()
                lastPoint.pressure = event.pressure()
                lastPoint.rotation = event.rotation()

            break
        elif index == QEvent.TabletRelease:
            if m_deviceDown and event.buttons() == Qt.NoButton:
                m_deviceDown = False
            update()
            break
        else:
            break

    event.accept()

We get three kind of events to this function: TabletPress, TabletRelease, and TabletMove, which are generated when a drawing tool is pressed down on, lifed up from, or moved across the tablet. We set m_deviceDown to true when a device is pressed down on the tablet; we then know that we should draw when we receive move events. We have implemented updateBrush() to update m_brush and m_pen depending on which of the tablet event properties the user has chosen to pay attention to. The updateCursor() function selects a cursor to represent the drawing tool in use, so that as you hover with the tool in proximity of the tablet, you can see what kind of stroke you are about to make.

def updateCursor(self, event):

    cursor = QCursor()
    if event.type() != QEvent.TabletLeaveProximity:
        if event.pointerType() == QPointingDevice.PointerType.Eraser:
            cursor = QCursor(QPixmap(":/images/cursor-eraser.png"), 3, 28)
        else:
            switch (event.deviceType()) {
            elif m_lineWidthValuator == QInputDevice.DeviceType.Stylus:
                if event.pointingDevice().capabilities().testFlag(QPointingDevice.Capability.Rotation):
                    origImg = QImage(":/images/cursor-felt-marker.png")
                    img = QImage(32, 32, QImage.Format_ARGB32)
                    solid = m_color
                    solid.setAlpha(255)
                    img.fill(solid)
                    painter = QPainter(img)
                    transform = painter.transform()
                    transform.translate(16, 16)
                    transform.rotate(event.rotation())
                    painter.setTransform(transform)
                    painter.setCompositionMode(QPainter.CompositionMode_DestinationIn)
                    painter.drawImage(-24, -24, origImg)
                    painter.setCompositionMode(QPainter.CompositionMode_HardLight)
                    painter.drawImage(-24, -24, origImg)
                    painter.end()
                    cursor = QCursor(QPixmap.fromImage(img), 16, 16)
                else:
                    cursor = QCursor(QPixmap(":/images/cursor-pencil.png"), 0, 0)

                break
            elif m_lineWidthValuator == QInputDevice.DeviceType.Airbrush:
                cursor = QCursor(QPixmap(":/images/cursor-airbrush.png"), 3, 4)
                break
            else:
                break



    setCursor(cursor)

If an art pen (RotationStylus) is in use, updateCursor() is also called for each TabletMove event, and renders a rotated cursor so that you can see the angle of the pen tip.

Here is the implementation of paintEvent():

def initPixmap(self):

    dpr = devicePixelRatio()
    newPixmap = QPixmap(qRound(width() * dpr), qRound(height() * dpr))
    newPixmap.setDevicePixelRatio(dpr)
    newPixmap.fill(Qt.white)
    painter = QPainter(newPixmap)
    if not m_pixmap.isNull():
        painter.drawPixmap(0, 0, m_pixmap)
    painter.end()
    m_pixmap = newPixmap

def paintEvent(self, event):

    if m_pixmap.isNull():
        initPixmap()
    painter = QPainter(self)
    pixmapPortion = QRect(event.rect().topLeft() * devicePixelRatio(),()
                                event.rect().size() * devicePixelRatio())
    painter.drawPixmap(event.rect().topLeft(), m_pixmap, pixmapPortion)

The first time Qt calls paintEvent(), m_pixmap is default-constructed, so QPixmap::isNull() returns true. Now that we know which screen we will be rendering to, we can create a pixmap with the appropriate resolution. The size of the pixmap with which we fill the window depends on the screen resolution, as the example does not support zoom; and it may be that one screen is high DPI while another is not. We need to draw the background too, as the default is gray.

After that, we simply draw the pixmap to the top left of the widget.

Here is the implementation of paintPixmap():

def paintPixmap(self, painter, event):

    maxPenRadius = pressureToWidth(1.0)
    painter.setRenderHint(QPainter.Antialiasing)
    switch (event.deviceType()) {
        elif index == QInputDevice.DeviceType.Airbrush:

                painter.setPen(Qt.NoPen)
                grad = QRadialGradient(lastPoint.pos, m_pen.widthF() * 10.0)
                color = m_brush.color()
                color.setAlphaF(color.alphaF() * 0.25)
                grad.setColorAt(0, m_brush.color())
                grad.setColorAt(0.5, Qt.transparent)
                painter.setBrush(grad)
                radius = grad.radius()
                painter.drawEllipse(event.position(), radius, radius)
                update(QRect(event.position().toPoint() - QPoint(radius, radius), QSize(radius * 2, radius * 2)))

            break
        elif index == QInputDevice.DeviceType.Puck:
        elif index == QInputDevice.DeviceType.Mouse:

                error = QString(tr("This input device is not supported by the example."))
#if QT_CONFIG(statustip)
                status = QStatusTipEvent(error)
                QCoreApplication.sendEvent(self, status)
#else
                qWarning() << error
#endif

            break
        else:

                error = QString(tr("Unknown tablet device - treating as stylus"))
#if QT_CONFIG(statustip)
                status = QStatusTipEvent(error)
                QCoreApplication.sendEvent(self, status)
#else
                qWarning() << error
#endif

            Q_FALLTHROUGH()
        elif index == QInputDevice.DeviceType.Stylus:
            if event.pointingDevice().capabilities().testFlag(QPointingDevice.Capability.Rotation):
                m_brush.setStyle(Qt.SolidPattern)
                painter.setPen(Qt.NoPen)
                painter.setBrush(m_brush)
                poly = QPolygonF()
                halfWidth = pressureToWidth(lastPoint.pressure)
                QPointF brushAdjust(qSin(qDegreesToRadians(-lastPoint.rotation)) * halfWidth,
                                    qCos(qDegreesToRadians(-lastPoint.rotation)) * halfWidth)
                poly << lastPoint.pos + brushAdjust
                poly << lastPoint.pos - brushAdjust
                halfWidth = m_pen.widthF()
                brushAdjust = QPointF(qSin(qDegreesToRadians(-event.rotation())) * halfWidth,
                                      qCos(qDegreesToRadians(-event.rotation())) * halfWidth)
                poly << event.position() - brushAdjust
                poly << event.position() + brushAdjust
                painter.drawConvexPolygon(poly)
                update(poly.boundingRect().toRect())
            else:
                painter.setPen(m_pen)
                painter.drawLine(lastPoint.pos, event.position())
                update(QRect(lastPoint.pos.toPoint(), event.position().toPoint()).normalized()
                       .adjusted(-maxPenRadius, -maxPenRadius, maxPenRadius, maxPenRadius))

            break

In this function we draw on the pixmap based on the movement of the tool. If the tool used on the tablet is a stylus, we want to draw a line from the last-known position to the current position. We also assume that this is a reasonable handling of any unknown device, but update the status bar with a warning. If it is an airbrush, we want to draw a circle filled with a soft gradient, whose density can depend on various event parameters. By default it depends on the tangential pressure, which is the position of the finger wheel on the airbrush. If the tool is a rotation stylus, we simulate a felt marker by drawing trapezoidal stroke segments.

elif index == QInputDevice.DeviceType.Airbrush:

        painter.setPen(Qt.NoPen)
        grad = QRadialGradient(lastPoint.pos, m_pen.widthF() * 10.0)
        color = m_brush.color()
        color.setAlphaF(color.alphaF() * 0.25)
        grad.setColorAt(0, m_brush.color())
        grad.setColorAt(0.5, Qt.transparent)
        painter.setBrush(grad)
        radius = grad.radius()
        painter.drawEllipse(event.position(), radius, radius)
        update(QRect(event.position().toPoint() - QPoint(radius, radius), QSize(radius * 2, radius * 2)))

    break

In updateBrush() we set the pen and brush used for drawing to match m_alphaChannelValuator, m_lineWidthValuator, m_colorSaturationValuator, and m_color. We will examine the code to set up m_brush and m_pen for each of these variables:

def updateBrush(self, event):

    hue, = int()
    m_color.getHsv(hue, saturation, value, alpha)
    vValue = int(((event.yTilt() + 60.0) / 120.0) * 255)
    hValue = int(((event.xTilt() + 60.0) / 120.0) * 255)

We fetch the current drawingcolor’s hue, saturation, value, and alpha values. hValue and vValue are set to the horizontal and vertical tilt as a number from 0 to 255. The original values are in degrees from -60 to 60, i.e., 0 equals -60, 127 equals 0, and 255 equals 60 degrees. The angle measured is between the device and the perpendicular of the tablet (see QTabletEvent for an illustration).

        if m_alphaChannelValuator == PressureValuator:
            m_color.setAlphaF(event.pressure())
            break
        elif m_alphaChannelValuator == TangentialPressureValuator:
            if event.deviceType() == QInputDevice.DeviceType.Airbrush:
                m_color.setAlphaF(qMax(0.01, (event.tangentialPressure() + 1.0) / 2.0))
else:
                m_color.setAlpha(255)
            break
        elif m_alphaChannelValuator == TiltValuator:
            m_color.setAlpha(std.max(std.abs(vValue - 127),
                                      std::abs(hValue - 127)))
            break
        else:
            m_color.setAlpha(255)

The alpha channel of QColor is given as a number between 0 and 255 where 0 is transparent and 255 is opaque, or as a floating-point number where 0 is transparent and 1.0 is opaque. pressure() returns the pressure as a qreal between 0.0 and 1.0. We get the smallest alpha values (i.e., the color is most transparent) when the pen is perpendicular to the tablet. We select the largest of the vertical and horizontal tilt values.

if m_colorSaturationValuator == VTiltValuator:
    m_color.setHsv(hue, vValue, value, alpha)
    break
elif m_colorSaturationValuator == HTiltValuator:
    m_color.setHsv(hue, hValue, value, alpha)
    break
elif m_colorSaturationValuator == PressureValuator:
    m_color.setHsv(hue, int(event.pressure() * 255.0), value, alpha)
    break
else:

The color saturation in the HSV color model can be given as an integer between 0 and 255 or as a floating-point value between 0 and 1. We chose to represent alpha as an integer, so we call setHsv() with integer values. That means we need to multiply the pressure to a number between 0 and 255.

if m_lineWidthValuator == PressureValuator:
    m_pen.setWidthF(pressureToWidth(event.pressure()))
    break
elif m_lineWidthValuator == TiltValuator:
    m_pen.setWidthF(std.max(std.abs(vValue - 127),
                             std::abs(hValue - 127)) / 12)
    break
else:
    m_pen.setWidthF(1)

The width of the pen stroke can increase with pressure, if so chosen. But when the pen width is controlled by tilt, we let the width increase with the angle between the tool and the perpendicular of the tablet.

if event.pointerType() == QPointingDevice.PointerType.Eraser:
    m_brush.setColor(Qt.white)
    m_pen.setColor(Qt.white)
    m_pen.setWidthF(event.pressure() * 10 + 1)
else:
    m_brush.setColor(m_color)
    m_pen.setColor(m_color)

We finally check whether the pointer is the stylus or the eraser. If it is the eraser, we set the color to the background color of the pixmap and let the pressure decide the pen width, else we set the colors we have decided previously in the function.

TabletApplication Class Definition#

We inherit QApplication in this class because we want to reimplement the event() function.

class TabletApplication(QApplication):

    Q_OBJECT
# public
    QApplication.QApplication = using()
    bool event(QEvent event) override
    def setCanvas(canvas):
        { m_canvas = canvas; }
# private
    m_canvas = None

TabletApplication exists as a subclass of QApplication in order to receive tablet proximity events and forward them to TabletCanvas. The TabletEnterProximity and TabletLeaveProximity events are sent to the QApplication object, while other tablet events are sent to the QWidget ‘s event() handler, which sends them on to tabletEvent() .

TabletApplication Class Implementation#

Here is the implementation of event():

def event(self, QEvent event):

    if (event.type() == QEvent.TabletEnterProximity or
        event.type() == QEvent.TabletLeaveProximity) {
        m_canvas.setTabletDevice(QTabletEvent(event))
        return True

    return QApplication.event(event)

We use this function to handle the TabletEnterProximity and TabletLeaveProximity events, which are generated when a drawing tool enters or leaves the proximity of the tablet. Here we call TabletCanvas::setTabletDevice(), which then calls updateCursor(), which will set an appropriate cursor. This is the only reason we need the proximity events; for the purpose of correct drawing, it is enough for TabletCanvas to observe the device() and pointerType() in each event that it receives.

The `` main()``

function#

Here is the example’s main() function:

if __name__ == "__main__":

    app = TabletApplication(argv, args)
    canvas = TabletCanvas()
    app.setCanvas(canvas)
    mainWindow = MainWindow(canvas)
    mainWindow.resize(500, 500)
    mainWindow.show()
    sys.exit(app.exec())

Here we create a MainWindow and display it as a top level window. We use the TabletApplication class. We need to set the canvas after the application is created. We cannot use classes that implement event handling before an QApplication object is instantiated.

Example project @ code.qt.io