我想将QChart
(其核心为QGraphicsWidget
)呈现给特定的画家,例如QSvgGenerator
。
我已阅读以下主题https://forum.qt.io/topic/38352/rendering-qgraphicsitem-without-qgraphicsscene/2并在我的代码中实现了它:
QBuffer b;
QSvgGenerator p;
p.setOutputDevice(&b);
QSize s = app->chart()->size().toSize();
p.setSize(s);
p.setViewBox(QRect(0,0,s.width(),s.height()));
QPainter painter;
painter.begin(&p);
painter.setRenderHint(QPainter::Antialiasing);
app->chart()->paint(&painter, 0, 0); // This gives 0 items in 1 group
m_view->render(&painter); // m_view has app->chart() in it, and this one gives right image
qDebug() << "Copied";
painter.end();
QMimeData * d = new QMimeData();
d->setData("image/svg+xml",b.buffer());
QApplication::clipboard()->setMimeData(d,QClipboard::Clipboard);
有两行评论:第一行是直接绘制QChart
,第二行是渲染QGraphicsView
。
我已经尝试过使用setViewBox
,将其设置为巨大的价值并没有帮助。如果我使用QImage
而不是QSvgGenerator
,效果是一样的,我得到空白图片。
所以问题是为什么QChart->paint()
给我空画?
编辑:可以在bitbucket上找到工作代码:https://bitbucket.org/morodeer/charts_test_2/commits/b1eee99736beb5e43eae2a40ae116ee07e01558f
答案 0 :(得分:3)
我仍然不明白核心内部发生了什么,但我找到了一种方法让它发挥作用。
app->chart()->paint(&painter, 0, 0);
应改为
app->chart()->scene()->render(&painter, 0, 0);
看起来QChart并不真正包含其中的任何内容,但会将项目添加到父级场景中。因此,如果你需要渲染它而不像我一样添加到QGraphicsView,你还应该创建QGraphicsScene
并向其添加图表:
m_scene = new QGraphicsScene();
m_scene->addItem(m_chart);
,然后你就可以渲染图表的场景了。
答案 1 :(得分:0)
因为这或多或少是我发现的关于如何从QChart渲染图表的唯一提示,我花了很长时间才弄明白,我想要分享我的代码。
这是PyQt5的python,但应该很容易翻译成纯C ++;) 另请注意,我的QChart是QChartView小部件的一部分。
chart = QtChart.QChart()
chart_view = QtChart.QChartView(chart)
...
# the desired size of the rendering
# in pixels for PNG, in pt for SVG
output_size = QtCore.QSize(800,600)
output_rect = QtCore.QRectF(QtCore.QPointF(0,0), QtCore.QSizeF(output_size)) # cast to float
if output_svg:
svg = QtSvg.QSvgGenerator()
svg.setFileName(filename)
svg.setTitle("some title")
svg.setSize(output_size)
svg.setViewBox(output_rect)
canvas = svg
else:
image = QtGui.QImage(output_size, QtGui.QImage.Format_ARGB32)
image.fill(QtCore.Qt.transparent)
canvas = image
# uncomment to hide background
#chart.setBackgroundBrush(brush = QtGui.QBrush(QtCore.Qt.NoBrush))
# resize the chart, as otherwise the size/scaling of the axes etc.
# will be dependent on the size of the chart in the GUI
# this way, a consistent output size is enforced
original_size = chart.size()
chart.resize(output_rect.size())
painter = QtGui.QPainter()
painter.begin(canvas)
# enable antialiasing (painter must be active, set this after painter.begin())
# only affects PNG output
painter.setRenderHint(QtGui.QPainter.Antialiasing)
chart.scene().render(painter, source=output_rect, target=output_rect, mode=QtCore.Qt.IgnoreAspectRatio)
painter.end()
chart.resize(original_size)
if type(canvas) == QtGui.QImage:
canvas.save(filename)
但是如果你正在使用python,那么可能更容易使用matplotlib,它提供了更多的功能和格式,也可以集成到PyQt-GUI中。