Inverted colors effect with the Qt graphics view framework
Article Metadata
Code Example
Source file: Media:GraphicsEffect-Inverted.zip
Compatibility
Platform(s): any
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.
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



(no comments yet)