Thursday, July 31, 2014

Change color on SVG item in Qt

This is a neat trick that can be good to know, found the solution in StackOverflow:
http://stackoverflow.com/questions/15123544/change-the-color-of-an-svg-in-qt/15124080#15124080

If you have for example an arrow that needs to be in different colors at different times in a Qt application, it's possible to change the color of an SVG item instead of adding several SVG items with different colors. 

QColor weightOutreachSupportArrowHorisontalColor = getWeightOutreachSupportArrowHorisontalColor();
yAxisIndicator_ = QSharedPointer<QGraphicsSvgItem>(new QGraphicsSvgItem(":/Icon/Icon/Arrow_x_30_30.svg",0));
QGraphicsColorizeEffect* weightOutreachSupportArrowHorisontalColorEffect = new QGraphicsColorizeEffect();
weightOutreachSupportArrowHorisontalColorEffect->setColor(weightOutreachSupportArrowHorisontalColor);
yAxisIndicator_->setGraphicsEffect(weightOutreachSupportArrowHorisontalColorEffect);
yAxisIndicator_->setZValue(100);
yAxisIndicator_->rotate(90);
yAxisIndicator_->setVisible(false);

scene_->addItem(yAxisIndicator_.data());

1 comment:

Unknown said...

the very best solution for me :) great job.
that's realy modify QGraphicsSvgItem color.

UILoader::UILoader(QWidget *parent):QGraphicsView(parent){
item = new QGraphicsSvgItem(QLatin1String(":/loader.svg"));

this->setHorizontalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );
this->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );
this->setStyleSheet( "QGraphicsView { border-style: none; }" );
}

UILoader::rotateLoader(){
item->setRotation(item->rotation()+10);
float angle=-float(item->rotation())/180.0*3.1415926535897;
item->setX(-w*(cos(angle)-1)/2-sin(angle)*h/2);
item->setY(w*(sin(angle))/2-(cos(angle)-1)*h/2);
}

UILoader::putLoader(QString color){
W=this->width();
H=this->height();
connect(&loop,SIGNAL(timeout()),this,SLOT(rotateLoader()));

float dx=W/float(item->boundingRect().width());
float dy=H/float(item->boundingRect().height());
float min=std::min(dx,dy);
w=std::min(W,H);
h=w;

item->setScale(min);
QSP = QSharedPointer(item);
QGraphicsColorizeEffect* QGCE = new QGraphicsColorizeEffect();
QGCE->setColor(Qt::blue);
QSP->setGraphicsEffect(QGCE);

scene=new QGraphicsScene();
scene->setSceneRect((w-W)/2,(h-H)/2,W,H);
this->setScene(scene);
this->setRenderHints(QPainter::Antialiasing);
scene->addItem(QSP.data());
this->show();

loop.start(50);
}