- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 262字
- 2021-08-27 18:31:07
What just happened?
When the view needs to display the scene, it calls the paint() function of each visible item and provides three arguments: a QPainter pointer that should be used for painting, a QStyleOptionGraphicsItem pointer that contains painting-related parameters for this item, and an optional QWidget pointer that may point to the currently painted widget. In the implementation of the function, we start with setting a cosmetic pen in the painter so that the line width of our graph is always 1. Next, we calculate the number of points in the graph and save it to the steps variable. Then, we create a variable to store the previous point of the graph and initialize it with the position of the first point of the graph (corresponding to x = 0). Next, we iterate through points, calculate x and y for each point, and then use the painter object to draw a line from the previous point to the current point. After this, we update the value of the previousPoint variable. We use the Q_UNUSED() macro to suppress compiler warnings about unused arguments and to indicate that we, intentionally, didn't use them.
Edit the constructor of our View class to create an instance of our new item:
SineItem *item = new SineItem(); scene()->addItem(item);
The application should display the sine graph now, but it is very small:
We should add a way for users to scale our view using the mouse wheel. However, before we get to this, you need to learn a little more about event handling.