This is the most basic of basic tutorials when it comes to computer programming. It is virtually done to death. The basic idea is for you as the programmer to be able to send a message to the computer and have it return the message to you as output. Originally, this would be done via command-line or command-prompt, a scary black void of an interface. So in this case, I’ll show you how to actually engage the user by hooking into the default GUI mainWindow.
- Open Qt Creator 2.8.0
- Go to File>New File Or Project
- Choose Projects>Applications>Qt Gui Application
- For “Introduction and Project Location”, name your project “Hello World”, and browse to a memorable location where to create it in.
- For “Kit Selection”, check “Qt 4.8.5 (minGW)”
Note: there may be other kits available to you depending on if you have those installed
- For “Class Information”, keep defaults.
- For “Project Management”, keep defaults. Click Finish.
- Qt Creator automatically loads newly generated “mainwindow.cpp” by default, ready to be edited.
- Note: If you don’t have a debugger, then you won’t be able to debug.
So when you run it, set it to Release mode. If there are any serious bugs, the compiler will still throw an error.
- Hit Run.
- At the very minimum, you will have a window that can run. But it doesn’t really do anything useful.
- Close the window or Stop (the red square in the debugger tool strip).
- Now, let’s actually do some real coding. Click on mainWindow.h to open it in the editor.
- Make the following changes to mainWindow.h:
Addprotected: void paintEvent(QPaintEvent *);
- Now that you have overriden the mainWindow widget’s default paintEvent, you must provide your own method for painting. Open mainWindow.cpp in the editor.
Add#include "QPainter"
and
void MainWindow::paintEvent(QPaintEvent *) { QPainter painter(this); painter.drawText(QRect(20,20,200,200),"Hello World"); painter.end(); }
- Save and run.
- If everything is set properly, what you get is the same basic mainWindow plus your newfound ability to paint on the widget.
I hope you found that helpful. This is your quickstart intro to QPainter, which is quite robust. You can now experiment with background colors, fonts, placement, and other drawing features. Happy coding!