Search code examples
qtdrawingqt5

Qt - Draw on canvas


I am trying to write a program using Qt5 that allows users to draw on canvas like paint. I know that the program has to handle events such as mousePressEvent(), mouseReleaseEvent(), and mouseMoveEvent(). But I am not able to figure out how to use them.

Can you guys give me a simple example on this?


Solution

  • I have provided an example that shows this. https://bitbucket.org/jsuppe/qt-paint

    What this example shows is:

    • Create a widget & handle mouse events & paint event
    • The widget contains a QImage which is the size of the widget.
    • Write to the QImage the pixel coordinates when the mouse events occur
    • Tell the widget to re-paint when pixels are changed on the QImage
    • In the paintEvent I paint my QImage

    I hope this helps

    Update: I've since changed this sample to using QPainterPath to draw to the QImage. The old method is still there drawing pixels directly, but out of the box there is a lot more function with QPainterPath. I've also added a QML demo here: https://bitbucket.org/jsuppe/qt-paint-2