svg_util.h
Go to the documentation of this file.
1 /*
2  * This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this
4  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5  */
6 
7 #ifndef PJ_SVG_UTIL_H
8 #define PJ_SVG_UTIL_H
9 
10 #ifdef QT_NO_SVGRENDERER
11 #error "QT_NO_SVGRENDERER defined"
12 #endif
13 
14 #include <QtSvg>
15 #include <QFile>
16 #include <QIcon>
17 #include <QTextStream>
18 #include <QByteArray>
19 #include <QPainter>
20 #include <QPixmap>
21 #include <QDebug>
22 
23 // Useful function to change the color of SVG icons programmatically.
24 // Useful to switch between dark view and light view.
25 // To work, the SVG file must use the color #ffffff and #000000 only.
26 inline const QPixmap& LoadSvg(QString filename, QString style_name = "light")
27 {
28  static std::map<QString, QPixmap> light_images;
29  static std::map<QString, QPixmap> dark_images;
30  bool light_theme = style_name.contains("light");
31 
32  auto* stored_images = light_theme ? &light_images : &dark_images;
33 
34  auto it = stored_images->find(filename);
35  if (it == stored_images->end())
36  {
37  QFile file(filename);
38  file.open(QFile::ReadOnly | QFile::Text);
39  auto svg_data = file.readAll();
40  file.close();
41 
42  if (light_theme)
43  {
44  svg_data.replace("#000000", "#111111");
45  svg_data.replace("#ffffff", "#dddddd");
46  }
47  else
48  {
49  svg_data.replace("#000000", "#dddddd");
50  svg_data.replace("#ffffff", "#111111");
51  }
52  QByteArray content(svg_data);
53 
54  QSvgRenderer rr(content);
55  QImage image(64, 64, QImage::Format_ARGB32);
56  QPainter painter(&image);
57  image.fill(Qt::transparent);
58  rr.render(&painter);
59 
60  it = stored_images->insert({ filename, QPixmap::fromImage(image) }).first;
61  }
62  return it->second;
63 }
64 
65 #endif // PJ_SVG_UTIL_H
detail::first
auto first(const T &value, const Tail &...) -> const T &
Definition: compile.h:60
LoadSvg
const QPixmap & LoadSvg(QString filename, QString style_name="light")
Definition: svg_util.h:26


plotjuggler
Author(s): Davide Faconti
autogenerated on Sun Aug 11 2024 02:24:26