渲染 SVG 文件
SVG 图形可渲染到任何QPaintDevice 子类上,如QWidget 或QImage 。渲染 SVG 文件的最简单方法是使用QSvgWidget 或QSvgRenderer 。
使用 QSvgWidget
QSvgWidget 提供了一个显示 SVG 文件的便捷部件。
#include <QApplication> #include <QSvgWidget> int main(int argc, char *argv[]) { QApplication app(argc, argv); QSvgWidget svgWidget(QStringLiteral(":/images/example.svg")); svgWidget.setGeometry(100, 100, 400, 400); svgWidget.show(); return app.exec(); }
您还可以在构建后加载 SVG 文件:
#include <QApplication> #include <QSvgWidget> int main(int argc, char *argv[]) { QApplication app(argc, argv); QSvgWidget *svgWidget = new QSvgWidget; svgWidget->load(QStringLiteral(":/images/example.svg")); svgWidget->show(); return app.exec(); }
使用 QSvgRenderer
使用QSvgRenderer 可将 SVG 内容渲染到任何QPaintDevice 上。
#include <QApplication> #include <QSvgRenderer> #include <QImage> #include <QPainter> #include <QLabel> #include <QPixmap> int main(int argc, char *argv[]) { QApplication app(argc, argv); QSvgRenderer renderer(QStringLiteral(":/images/example.svg")); if (renderer.isValid()) { QImage image(400, 400, QImage::Format_ARGB32_Premultiplied); image.fill(Qt::transparent); QPainter painter(&image); renderer.render(&painter); QLabel label; label.setPixmap(QPixmap::fromImage(image)); label.resize(400, 400); label.show(); return app.exec(); } return 1; }
您还可以使用QSvgRenderer 直接在自定义 widget 的绘制事件中渲染 SVG:
// In your widget's header file: #include <QSvgRenderer> class MyWidget : public QWidget { Q_OBJECT public: MyWidget(QWidget *parent = nullptr) : QWidget(parent), renderer(QStringLiteral(":/images/example.svg")) {} protected: void paintEvent(QPaintEvent *) override { QPainter painter(this); renderer.render(&painter); } private: QSvgRenderer renderer; };
这些方法允许您在 Qt 支持的所有绘制设备上渲染 SVG 文件,包括QWidget 和QImage 。
渲染选项
QSvgRenderer 通过QtSvg::Option 枚举提供了渲染options 。通过这些选项,您可以控制 SVG 文件的解析和渲染方式。
渲染动画 SVG 文件
Qt SVG 模块支持渲染动画 SVG 文件。有关如何处理 SVG 动画的详细信息,请参阅QSvgRenderer 类文档。
另请参阅 Qt 中的矢量图像格式和扩展功能。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.