how to print a QGraphicsScene that has text and gr

2019-07-04 06:08发布

问题:

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 is using a font size defined in points, so scene->render() when I pass it a QPainter initialized with a QPrinter, has VERY large text.

How am I supposed to print a QGraphicsScene that has text on it?

edit:

Here is my current printing 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 doesn't appear to make any difference. The printer still thinks the text is huge, so for each text item only a tiny part of the first letter is printed.

回答1:

From the QPrinter docs it sounds like you have to specify font sizes in pixels to get text and graphics to match up. Note that QFont has a setPixelSize method.



回答2:

Setting up the QPrinter:

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

If you are setting up the QPrinter object using a QPrintDialog then the code should be something like this:

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

After this, the program should output the DPI of the selected printer. In my case it prints out 600.

If you aren't using the QPrintDialog, you should use the QPrinter constructor as shown above and then call setResolution(DPI) with the known DPI of your printer.

This should result in fonts that are rendered correctly.

Update:

Now that the weekend is here, I finally had time to properly consider this issue :) Although technically correct for setting up a QPrinter, the above solution is not practical for Graphics scenes that include text specified in point sizes. Since all graphic items are specified in pixel coordinates, it only makes sense to specify font sizes in pixels as well to ensure that fonts appear exactly as expected when mixed with other graphic primitives.

There is no need to be concerned about the size of the text on different monitors as the graphics items themselves are not resolution independent. The view can specify scale translations to deal with different resolution and DPI monitors.

When printing, by default, the QPrinter scales to fit the entire scene to the page. Which makes sense since a 100 x 100 square on a 600 DPI printer is goint to be 1/6th of an inch wide on your paper :)