Printing complex widgets in Qt

2019-08-31 23:02发布

问题:

I have a complex widget with tons of different subwidgets, e.g. subclasses of QLabel. I want to print this widget, but obviously I do not want to print the background, I want to print with differing text colors or have the style of frames slightly modified.

As I do not really want to iterate through all subwidgets with a special "print" function, which I would need to attach to all widgets (how to add "print" to a QLabel?), I would like to use paintEvent.

If I have a hierarchy MyWidget -> derived from -> some QWidget, I would like to insert a sublayer MyWidget -> MyPrintWidget -> some QWidget, where myPrintWidget::paintEvent would check, if the current print is going to the screen (thus call QWidget::paintEvent), else if we are printing to the printer, call some function MyPrintWidget::drawWidget instead.

  1. Is this the right way to print-enable a widget?
  2. How can I figure out in paintEvent, that I'm printing to a printer instead of the screen?
  3. Is there a good example of printing complex widgets?

回答1:

  1. Is this the right way to print-enable a widget?

QWidget::render() will render a widget and all of its children to a QPaintDevice, which a QPrinter is. For printing, all you need to do is set the widgets stylesheet correctly before calling render on the printer device. You should be able to set it back immediately afterwards if you're reusing an on-screen widget.

  1. How can I figure out in paintEvent, that I'm printing to a printer instead of the screen?

You might be able to figure it out by looking at the various QPaintDevice properties, but I'd try to avoid relying on that functionality.

  1. Is there a good example of printing complex widgets?

I don't know of anything that does what you're attempting to do.



标签: qt printing qt4