×
Namespaces

Variants
Actions

Inverted colors effect with the Qt graphics view framework

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Code ExampleCompatibility
Platform(s): any
Symbian
Article
Keywords: QGraphicsEffect, QGraphicsView
Created: gnuton (24 Dec 2010)
Last edited: hamishwillee (11 Oct 2012)

Introduction

This article shows how to inverts the color of a graphics item by applying custom graphics effect. Qt Graphics View Framework offers a convenient way to apply graphics effect to Graphics Items.

Qt-GraphicsEffect-Inverted.jpg

Code

Since the invert effect is not available in Qt, QGraphicsEffect has been subclassed to achieve the desired effect.

#ifndef QGRAPHICSINVERTCOLORSEFFECT_H
#define QGRAPHICSINVERTCOLORSEFFECT_H
 
#include <QGraphicsEffect>
#include <QPainter>
 
class QGraphicsInvertColorsEffect : public QGraphicsEffect {
public:
QGraphicsInvertColorsEffect(QObject *parent = 0) : QGraphicsEffect(parent)
{
}
 
~QGraphicsInvertColorsEffect()
{
}
 
protected:
void draw(QPainter *painter)
{
QPoint offset;
 
QPixmap pixmap = sourcePixmap(Qt::LogicalCoordinates, &offset);
if (pixmap.isNull())
return;
 
QImage img = pixmap.toImage();
img.invertPixels();
painter->drawImage(boundingRect(), img);
}
};
#endif // QGRAPHICSINVERTCOLORSEFFECT_H

And the new class has been used in this way

#include <QtGui/QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QGraphicsEffect>
#include "QGraphicsInvertColorEffect.h"
 
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//a.setGraphicsSystem("raster");
QGraphicsView view;
view.setScene(new QGraphicsScene);
 
QGraphicsPixmapItem *p = view.scene()->addPixmap(QPixmap(":/meditate.png"));
 
QGraphicsInvertColorsEffect opacity;
p->setGraphicsEffect(&opacity);
 
view.show();
return a.exec();
}


Source code

Code is available here: Media:‎GraphicsEffect-Inverted.zip

This page was last modified on 11 October 2012, at 04:17.
115 page views in the last 30 days.