QT, Change the color of the SVG dynamically

94 Views Asked by At

I have an SVG icon that I draw using QSvgRenderer, I need to change the color of the icon, I have seen uninspiring solutions online, i.e. opening the SVG file and modifying the style parameters and reloading the SVG, the problem lies in the fact that I have to make a transition of the icon color and therefore this solution is not very efficient.

Is there any better solution? I think so, since vector drawing is always done with a QPainter, so I tried this, but it doesn't work:

#include <QApplication>
#include <QMainWindow>
#include <QSvgRenderer>
#include <QPainter>
#include <QVBoxLayout>

class MyWidget : public QWidget {
public:
    MyWidget(QWidget *parent = nullptr) : QWidget(parent) {
        // Crea un QSvgRenderer e carica l'icona SVG
        renderer.load(QString("./Option.svg"));
    }

    protected:
        void paintEvent(QPaintEvent *event) override {
            QPainter painter(this);
            painter.setBrush(Qt::blue);
            renderer.render(&painter);
        }

    private:
        QSvgRenderer renderer;
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    QMainWindow mainWindow;
    mainWindow.setFixedSize(800, 600);

    MyWidget *myWidget = new MyWidget(&mainWindow);
    myWidget->setFixedSize(56, 56);

    mainWindow.setCentralWidget(myWidget);
    mainWindow.show();

    return app.exec();
}
0

There are 0 best solutions below