1

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.

IAmInPLS
  • 4,051
  • 4
  • 24
  • 57
Tatarinho
  • 754
  • 2
  • 11
  • 31
  • 1
    When you draw items on a computer screen, you specify the drawing in pixels rather than millimetres. Are you aiming for something you can print to a printer in millimetres, or are you trying to achieve an accurate millimetre dimension on screen? – docsteer Nov 09 '14 at 17:16
  • You need to know the screen resolution and physical width and height of the screen in order to know how to map the pixels. – Daniel Hedberg Nov 09 '14 at 17:35
  • Im trying to achieve an accurate millimetre dimension on screen. – Tatarinho Nov 10 '14 at 13:20

1 Answers1

2

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)
Community
  • 1
  • 1
BaCaRoZzo
  • 7,502
  • 6
  • 51
  • 82
  • Thanks for your reply. Unfortunately I can't use Qwt etc to achieve this in my project. But your formula can be helpful. Thanks – Tatarinho Nov 10 '14 at 13:19
  • I see. Well, consider also [this nice answer](http://stackoverflow.com/questions/26828636/efficiently-painting-physically-accurate-ruler-in-qt). The purpose was to draw a ruler but you can build on that (and my formula) to achieve your goal. – BaCaRoZzo Nov 10 '14 at 13:30