Game Programming using Qt 5 Beginner's Guide
上QQ阅读APP看书,第一时间看更新

Time for action – Taking the zoom level into account

Our graph currently contains points with integer x values because we set DX = 1. This is exactly what we want for the default level of zoom, but once the view is zoomed in, it becomes apparent that the graph's line is not smooth. We need to change DX based on the current zoom level. We can do this by adding the following code to the beginning of the paint() function():

const qreal detail = QStyleOptionGraphicsItem::levelOfDetailFromTransform(
    painter->worldTransform());
const qreal dx = 1 / detail;

Delete the DX constant and replace DX with dx in the rest of the code. Now, when you scale the view, the graph's line keeps being smooth because the number of points increases dynamically. The levelOfDetailFromTransform helper function examines the value of the painter's transformation (which is a combination of all transformations applied to the item) and returns the level of detail. If the item is zoomed in 2:1, the level of detail is 2, and if the item is zoomed out 1:2, the level of detail is 0.5.