Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Inverted colors effect with the Qt graphics view framework

From 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 01:17.
92 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×