qt 儲存為svg圖片
阿新 • • 發佈:2019-02-20
新增
#include <QtSvg/QSvgGenerator>
#include <QFileDialog>
QT += core gui svg
一些重要的標頭檔案以及宣告。
建立menu bar, 命名一個Save as SVG,新增一個slog,原始碼如下;
#include "basicshapewindow.h" #include "ui_basicshapewindow.h" #include <QtSvg/QSvgGenerator> #include <QFileDialog> BasicShapeWindow::BasicShapeWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::BasicShapeWindow) { ui->setupUi(this); } void BasicShapeWindow::paintEvent(QPaintEvent *event) { paintAll(); } void BasicShapeWindow::paintAll(QSvgGenerator *generator) { QPainter painter; if (generator) painter.begin(generator); else painter.begin(this); painter.setFont(QFont("Times", 14, QFont::Bold)); painter.drawText(QPoint(20, 30), "Testing"); painter.drawLine(QPoint(50, 60), QPoint(100, 100)); painter.setBrush(Qt::BDiagPattern); painter.drawRect(QRect(40, 120, 80, 30)); QPen ellipsePen; ellipsePen.setColor(Qt::red); ellipsePen.setStyle(Qt::DashDotLine); painter.setPen(ellipsePen); painter.drawEllipse(QPoint(80, 200), 50, 20); QPainterPath rectPath; rectPath.addRect(QRect(150, 20, 100, 50)); painter.setPen(QPen(Qt::red, 1, Qt::DashDotLine, Qt::FlatCap, Qt::MiterJoin)); painter.setBrush(Qt::yellow); painter.drawPath(rectPath); QPainterPath ellipsePath; ellipsePath.addEllipse(QPoint(200, 120), 50, 20); painter.setPen(QPen(QColor(79, 106, 25), 5, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin)); painter.setBrush(QColor(122, 163, 39)); painter.drawPath(ellipsePath); QImage image; image.load(":/head.png"); painter.drawImage(QPoint(150, 150), image); painter.end(); } BasicShapeWindow::~BasicShapeWindow() { delete ui; } void BasicShapeWindow::on_actionSave_as_triggered() { QString filePath = QFileDialog::getSaveFileName(this, "Save SVG", "", "SVG files (*.svg)"); if (filePath == "") return ; QSvgGenerator generator; generator.setFileName(filePath); generator.setSize(QSize(this->width(), this->height())); generator.setViewBox(QRect(0, 0, this->width(), this->height())); generator.setTitle("SVG Example"); generator.setDescription("This SVG file is generated by Qt."); paintAll(&generator); }