我正在尝试将QSvgGenerator
的输出放入字符串中,以便在HTML中内联使用。我可以使用.setFileName(...)
方法并将输出作为文件获取,但.setOutputDevice(&qbuffer)
不会向 qbuffer 添加任何内容(我可以使用qbuffer.write(...);
在QSvgGenerator
上调用scene.render(&painter);
渲染操作之前和之后将字符串写入缓冲区,并看到这些字符串正在进入缓冲区)。
下面的代码片段会很乐意写入文件,但不会给我一个 SVG 字符串,代码路径的唯一区别是一个使用.setFileName(...)
另一个使用.setOutputDevice(...)
.
QGraphicsScene scene;
QPen backgroundPen(Qt::black);
QRectF backgroundRect(-10,-10,20,20);
QBrush backgroundBrush(QColor(128,64,64));
scene.addRect(backgroundRect, backgroundPen, backgroundBrush);
QBuffer qbuffer;
qbuffer.open(QBuffer::ReadWrite);
QSvgGenerator svgGenerator;
if (argc >= 2)
{
svgGenerator.setFileName(argv[1]);
}
else
{
svgGenerator.setOutputDevice(&qbuffer);
}
svgGenerator.setSize(QSize(128,128));
svgGenerator.setTitle("Title");
svgGenerator.setDescription("Description");
QPainter painter( &svgGenerator );
scene.render( &painter );
qbuffer.seek(0);
QString s(qbuffer.readAll());
qInfo() << s;
Qt 5.9,Ubuntu 17.10,如果这很重要的话。
根据文档:
bool QPainter::end()
结束绘画。绘制时使用的任何资源都会被释放。你 通常不需要调用它,因为它是由析构函数调用的。
如果绘制器不再处于活动状态,则返回 true;否则返回 假。
在您的情况下,您必须完成绘画:
[...]
QPainter painter( &svgGenerator );
scene.render( &painter );
painter.end();
qbuffer.seek(0);
QString s(qbuffer.readAll());
qInfo() << s;
输出:
"<?xml version="1.0" encoding="UTF-8" standalone="no"?>n<svg width="45.1556mm" height="45.1556mm"n xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.2" baseProfile="tiny">n<title>Title</title>n<desc>Description</desc>n<defs>n</defs>n<g fill="none" stroke="black" stroke-width="1" fill-rule="evenodd" stroke-linecap="square" stroke-linejoin="bevel" >nn<g fill="none" stroke="#000000" stroke-opacity="1" stroke-width="1" stroke-linecap="square" stroke-linejoin="bevel" transform="matrix(1,0,0,1,0,0)"nfont-family="Cantarell" font-size="11" font-weight="400" font-style="normal" n>n</g>nn<g fill="none" stroke="#000000" stroke-opacity="1" stroke-width="1" stroke-linecap="square" stroke-linejoin="bevel" transform="matrix(6.09524,0,0,6.09524,64,64)"nfont-family="Cantarell" font-size="11" font-weight="400" font-style="normal" n>n</g>nn<g fill="#804040" fill-opacity="1" stroke="#000000" stroke-opacity="1" stroke-width="1" stroke-linecap="square" stroke-linejoin="bevel" transform="matrix(6.09524,0,0,6.09524,64,64)"nfont-family="Cantarell" font-size="11" font-weight="400" font-style="normal" n>n<rect x="-10" y="-10" width="20" height="20"/>n</g>nn<g fill="none" stroke="#000000" stroke-opacity="1" stroke-width="1" stroke-linecap="square" stroke-linejoin="bevel" transform="matrix(6.09524,0,0,6.09524,64,64)"nfont-family="Cantarell" font-size="11" font-weight="400" font-style="normal" n>n</g>nn<g fill="none" stroke="#000000" stroke-opacity="1" stroke-width="1" stroke-linecap="square" stroke-linejoin="bevel" transform="matrix(1,0,0,1,0,0)"nfont-family="Cantarell" font-size="11" font-weight="400" font-style="normal" n>n</g>n</g>n</svg>n"