Nominate our 2022 Qt Champions!

How to properly draw on a QGraphicsPixmapItem

  • I'm new with Qt and C++, I'm making a painting software. I'm not sure if I'm drawing correctly (performance/memory) on a Pixmap. I have a QGraphicsScene and a QGraphicsPixmapItem on it. Once I click on the scene I start drawing like this:


    bool ToolPen::eventFilter (QObject *obj, QEvent evt)
    if (evt->type() == QEvent::GraphicsSceneMousePress ||
    evt->type() == QEvent::GraphicsSceneMouseMove)
    auto scene = static_cast<GraphicsScene
    auto e = static_cast<QGraphicsSceneMouseEvent>(evt);

        // layer is QGraphicsPixmapItem
        auto layer = scene->selectedLayer();
        // I get pixmap  
        auto pm = layer->pixmap();
        // I draw on it
        QPainter painter(&pm);
        drawline(painter, e->scenePos().x(), e->scenePos().y(),
                          e->lastScenePos().x(), e->lastScenePos().y());
        // then I set pixmap again
        return true;
    return QObject::eventFilter(obj, evt);


    I've read if I need pixel manipulation its better to use QImage, but then I need to keep converting QImage to QPixmap all the time. So the solution I found to draw on a QPixmap is that (but looks weird at first because it seems it is duplicating the whole pixmap and setting it again instead of using the same one). Is that ok or there is a better way?

  • First of all you do not have to use eventFilter.

    You can directly override QGraphicsScene mousePress and MouseMove Event.

    To do so you have to subclass QGraphicsScene and then override Mouse Events.

    What do you want to archive with you PixmapItem ?

    As i can see you would like to draw a simple line into your GraphicsScene.
    I think you need no QGraphicsPixmapItem at all.
    You could simply subclass QGraphicsItem and override paint. There you can draw your line directly without any need of pixmaps.

  • Win32 had two types of bitmaps; device dependent and device independent. When used for painting controls you want to use device dependent bitmaps as it was trivial to copy contents (use BitBlt() to do this). Using a device independent bitmap would require a conversion process to make it compatible with the target (screen, printer, ...) which would be a performance hit if you had to do this every time you needed to paint a control.

    I have the impression that this was one of the big differences between QPixmap and QImage. If you are using this for rendering controls or part of paintEvent() I would stick to QPixmap.

    I noticed when looking through the sources for various window styles that QPixmap is frequently used. It is probably optimized for this sort of thing.

Log in to reply