11

How would you suggest to handle svg with QPixmap?

The construct QPixmap(":/myfile.svg"); then call of scaled() does not work. The QPixmap gets pixelised.

Thx.

Smar
  • 8,109
  • 3
  • 36
  • 48
Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134

4 Answers4

39

Now there is much simpler way without needing of SVG module

QIcon("filepath.svg").pixmap(QSize())

So simple and works fine. Atleast in my case it worked.

Yash
  • 6,644
  • 4
  • 36
  • 26
  • 1
    At least with respect to the limited use case of icons, **this should now be the accepted answer.** Note that the `QIcon::addFile()` method *also* implicitly accepts SVG files now, permitting each icon mode and state to be associated with its own SVG file. – Cecil Curry Jun 17 '17 at 05:10
  • This does not scale the SVG up, if it was smaller than this size, it stays the same. – ababak Apr 17 '20 at 14:51
  • 1
    This is great. But how do you achieve the same thing by creating a scalable icon from an bytearray containing SVG? – Eugene Gill Mar 06 '21 at 18:29
9

You should use SVGRenderer to render it onto a QImage. From there you can convert to a QPixmap with QPixmap::convertFromImage.

Troubadour
  • 13,334
  • 2
  • 38
  • 57
6

Something like that:

QSvgRenderer renderer(svg_file_name);
QPixmap pm(width, height);
pm.fill(fill_color);
QPainter painter(&pm);
renderer.render(&painter, pm.rect());
Sergey Galin
  • 426
  • 6
  • 8
0

On Qt5.12 i managed to display SVG icons without pixellisation in a QLabel:

QPixmap logoPixmap(":my-logo.svg"); // set your logo here
auto logoLabel = new QLabel(this);
logoLabel->setPixmap(logoPixmap);
logoLabel->setScaledContents(true);
logoLabel->setFixedSize(176, 61); // set your size here
mmerle
  • 451
  • 4
  • 10