How to print a QGraphicsScene with text and graphics

I have a QGraphicsScene that has graphics, as well as text drawn on it. When I try to print, the graphics are fine, but the text uses the font size defined in points, so scene->render() , when I pass it to a QPainter initialized with QPrinter , has VERY big text.

How can I print a QGraphicsScene with text on it?

edit:

Here is my current print code, where scene_ is my custom subclass of QGraphicsScene :

  QPrinter printer(QPrinter::HighResolution); QPrintDialog dialog(&printer, this); dialog.exec(); std::cout << printer.resolution() << std::endl; QPainter painter(&printer); scene_->render(&painter); 

The std: cout line has no meaning. The printer still thinks the text is huge, so only a small part of the first letter is printed for each text element.

+3
source share
2 answers

From QPrinter docs, it seems that you should specify the font size in pixels in order to get text and graphics. Note that QFont has a setPixelSize method.

+3
source

QPrinter setup:

By default, the QPrinter object QPrinter initialized with a screen resolution (usually 96 DPI) unless you specify QPrinter::HighResolution in the constructor, which will then use the resolution of the printer you are using.

If you create a QPrinter object using QPrintDialog , then the code should look something like this:

 QPrinter printer(QPrinter::HighResolution); QPrintDialog dialog(&printer, this); dialog.exec(); std::cout << printer.resolution() << std::endl; 

After that, the program should display the DPI of the selected printer. In my case, it prints 600.

If you are not using QPrintDialog , you should use the QPrinter constructor as shown above, and then call setResolution(DPI) with your printer’s known DPI.

This should lead to the correct display of fonts.

Update:

Now that the weekend is here, I finally managed to consider this issue correctly :) Although technically correct for QPrinter settings, the above solution is not practical for graphic scenes containing text set in dot sizes. Since all graphic elements are specified in pixel coordinates, it makes sense to also indicate font sizes in pixels to ensure that the fonts look exactly as expected in combination with other graphic primitives.

No need to worry about the size of the text on different monitors, since the graphic elements themselves are not independent of resolution. The view may indicate scale translations for working with various resolution and DPI monitors.

When printing by default, the QPrinter scale is suitable for the entire scene on the page. Which makes sense, since a 100 x 100 square on a 600 DPI printer has a width of 1/6 inch on your paper :)

+1
source

All Articles