Difference between visual dimensions on QGraphicsScene and SVG file generated using QSvgGenerator

49 Views Asked by At

I specifically added scene rect to understand where the scene border is. The screenshot shows that the text “Hello, World! This is a multiline text. 1111” extends beyond the stage boundary.

enter image description here

For some reason, the entire text is displayed in the SVG file, although the second screen clearly shows that some text should not be displayed in the SVG at all. It is also clear that, for some reason, the stage border is larger.

enter image description here

Why is there such a visual difference?

#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsTextItem>
#include <QFont>
#include <QPushButton>
#include <QSvgGenerator>
#include <QFileDialog>
#include <QMessageBox>
#include <QApplication>
#include <QVBoxLayout>

int main(int argc, char *argv[]) 
{
    QApplication app(argc, argv);
    QGraphicsScene scene;
    scene.setSceneRect(0, 0, 400, 400); 
    QGraphicsView view(&scene);
    view.show();
scene.addRect(scene.sceneRect(), QPen(Qt::black));
    QString text = "Hello, World! This is a multiline text. 1111";
    QFont font("Arial", 16);
    QGraphicsTextItem *textItem = scene.addText(text, font);
    textItem->setPos(50, 50); 
    view.fitInView(scene.sceneRect(), Qt::KeepAspectRatio);    
    QPushButton generateButton("Generate SVG");
    QObject::connect(&generateButton, &QPushButton::clicked, [&]() {    
        QString filePath = QFileDialog::getSaveFileName(nullptr, "Save SVG", "", "SVG files (*.svg)");
        if (filePath.isEmpty())
            return;
        QSvgGenerator svgGenerator;
        svgGenerator.setFileName(filePath);
        svgGenerator.setSize(QSize(400, 400)); 
        svgGenerator.setViewBox(QRect(0, 0, 400, 400));   
        QPainter painter;
        painter.begin(&svgGenerator);       
        QRectF sceneRect = scene.sceneRect();
        painter.drawRect(sceneRect);      
        scene.render(&painter);

        painter.end();
    });
    QWidget mainWindow;
    QVBoxLayout layout(&mainWindow);
    layout.addWidget(&view);
    layout.addWidget(&generateButton);
    mainWindow.setLayout(&layout);
    mainWindow.show();

    return app.exec();
}

The SVG file generated exactly the same dimensions. I opened it in different browsers, they all display the same file. There is a suspicion that I missed some settings for the scene. I used different types of fonts, the problem was the same everywhere.

0

There are 0 best solutions below