How it works...

In this example, we created a QImage widget when the program started. This widget acts as the canvas and will follow the size of the window whenever the window gets resized. In order to draw something on the canvas, we will need to use the mouse events provided by Qt. These events will tell us the position of the cursor, and we will be able to use this information to change the pixels on the canvas.

We use a Boolean variable called drawing to let the program know whether it should start drawing when a mouse button is pressed. In this case, when the left mouse button is pressed, the drawing variable will be set to true. We also save the current cursor position to the lastPoint variable when the left mouse button is pressed, so that Qt will know where it should start drawing. When the mouse moves, the mouseMoveEvent() event will be triggered by Qt. This is where we need to check whether the drawing variable is set to true. If it is, then QPainter can start drawing the lines onto the QImage widget based on the brush settings that we provide. The brush settings consist of brushColor and brushSize. These settings are being saved as variables and can be altered by selecting a different setting from the menu bar.

Please remember to call the update() function when the user is drawing on the canvas. Otherwise, the canvas will remain empty even though we have changed the pixel information of the canvas. We also have to call the update() function when we select File | Clear from the menu bar to reset our canvas.

In this example, we use QImage::save() to save the image file, which is very easy and straightforward. We use the file dialog to let the user decide where to save the image and its desired filename. Then, we pass the information to QImage, and it will do the rest by itself. If we don't specify the file format to the QImage::save() function, QImage will try to figure it out by looking at the extension of the desired filename.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset