Insert QwtPlot plot into a document (Qwt)
-
I need to insert a plot made using QwtPlot into a document as an image with high DPI (so that it can be printed). Is it possible (as far as I understand, inserting a vector image will not work)?
The code I tried is the following:
@QImage image(2000, 2000, QImage::Format_ARGB32);
image.setDotsPerMeterX(300/0.0254);
image.setDotsPerMeterY(300/0.0254);
image.setDevicePixelRatio(3.0);
QwtPlotRenderer renderer;
renderer.renderTo(plot, image);
QTextCursor cursor = editor->textCursor();
cursor.insertImage(image);@'plot' is a pointer to QwtPlot object. When I show the plot as a widget in my program, it looks normal. But in the editor the inserted image has wrong scale (both axes are 0 to 100) and devicePixelRatio is ignored (the image is rendered pixel-to-pixel, i.e. as a 2000x2000 bitmap in my example). In all examples I have found plots are simply exported to files, but I would like to insert the image directly.
-
After some research I have found what seems to be an absolutely weird bug. QwtPlotRenderer::exportTo(plot, filename, size, resolution) method used throughout Qwt examples works properly, but QwtPlotRenderer::renderDocument(plot, filename, size, resolution), which is called from QwtPlotRenderer::exportTo, does not. I copied the code of QwtPlotRenderer::exportTo to my program and tried to localize the problem. It boiled down to the following - a call to some QFileDialog static method is necessary for export to work.
This code works as expected:
@QImage image(500, 500, QImage::Format_ARGB32);
QwtPlotRenderer renderer;
QFileDialog::getSaveFileName(NULL);
renderer.renderTo(plot, image);@This code does not:
@QImage image(500, 500, QImage::Format_ARGB32);
QwtPlotRenderer renderer;
renderer.renderTo(plot, image);@QFileDialog::getSaveFileName(NULL) may be replaced with QFileDialog::getOpenFileName(NULL) or QFileDialog::getExistingDirectory(NULL).
Unfortunately, the problem with DPI settings seems to be unsolvable.
-
There are no replies, but for those who can stumble upon similar problems - there are solutions for both.
I have found that, for some reason, it is necessary to call QwtPlot::replot() before rendering QwtPlot object to an image.
The solution for creating a document with vector (or high-DPI raster) images for printing is to use QWebView. The plot is rendered to a file:
@QwtPlotRenderer renderer;
plot->replot();
renderer.renderDocument(plot, "test.svg", QSizeF(100, 100));
@After that the resulting image file can be referred to in an HTML page shown by QWebView. The page can be printed to a physical printer or a PDF document.