I have to paint a millimeter grid on my widget. Does any class exist that can help me to do that? I need it to paint some math charts.
Before reinventing the wheel please take in account some charting libraries as discussed here. Both QCustomPlot
and Qwt
are easy to include and not that difficult to customize. Both provide several examples; possibly one of them could be the solution addressing your issue.
If the available libraries don't fulfill your needs you can create your own solution by subclassing QWidget
and reimplementing the painEvent()
. QPainter
and QPainterPath
are key classes for the task.
Qt
provides a lot of interesting tutorials, especially "Basic Drawing Example" and "Painter Paths Example". Probably you would also enjoy this simple example or this one. Starting from these references you should be able to draw your grid easily.
Finally, the Graphics View Framework contains the QGraphicsScene
which (citing docs)
provides a surface for managing a large number of 2D graphical items.
Such a class has been used for charting purposes and grids, exploiting painting APIs introduced above. While using this class it is crucial, to guarantee an overall good performance, to draw the grid in the drawBackground()
function as done for instance here (or use a background bitmap).
All the API discussed work in pixels. If you are really concerned with exact millimeters representation on screen, you can exploit the QScreen
object, directly accessible from your qApp
pointer. It provides several functions, in particular physicalDotsPerInch()
(logicalDotsPerInch()
for Android since the other returns an infinite value on KitKat). A pixel approximation for a millimeter can be calculated as follows:
int dotPerMillimeter = qRound(qApp->primaryScreen()->physicalDotsPerInch() / 25.4)