A sample highlighting QGraphicsEffect

From Qt Wiki
Jump to: navigation, search


While learning Qt, I wrote this sample highlighting graphics effect to be used with rectangular QGraphicsPixmapItem... and I use this post just to learn how to publish a wiki page here too.. ;-)



#include <QtGui>

class HighlightEffect : public QGraphicsEffect
 Q_PROPERTY( QColor color READ color WRITE setColor )
 Q_PROPERTY( QPointF offset READ offset WRITE setOffset )

  HighlightEffect( qreal offset = 1.5 );
  virtual QRectF boundingRectFor( const QRectF& sourceRect; ) const;
  QColor color() const { return mColor;}
  void setColor( QColor& color; ) { mColor = color;}
  QPointF offset() const { return mOffset;}
  void setOffset( QPointF offset ) { mOffset = offset;}

  virtual void draw( QPainter *painter ); // , QGraphicsEffectSource *source );

  QColor mColor;
  QPointF mOffset;

#endif // HIGHLIGHT_H


#include "highlight.h"

HighlightEffect::HighlightEffect( qreal offset ) :
 mColor( 255, 255, 0, 128 ), // yellow, semi-transparent
 mOffset( offset, offset ) {}

QRectF HighlightEffect::boundingRectFor( const QRectF& sourceRect; ) const
 return sourceRect.adjusted( -mOffset.x(), -mOffset.y(), mOffset.x(), mOffset.y() );

void HighlightEffect::draw( QPainter* painter )
 QPoint offset;
 QPixmap pixmap;

 // if ( sourceIsPixmap() ) // doesn't seems to work, return false
 // {
 // No point in drawing in device coordinates (pixmap will be scaled anyways).
 pixmap = sourcePixmap( Qt::LogicalCoordinates, &offset; );

 QRectF bound = boundingRectFor( pixmap.rect() );

 painter->setPen( Qt::NoPen );
 painter->setBrush( mColor );
 QPointF p( offset.x()-mOffset.x(), offset.y()-mOffset.y() );
 bound.moveTopLeft( p );
 painter->drawRoundedRect( bound, 5, 5, Qt::RelativeSize );
 painter->drawPixmap( offset, pixmap );

The strange thing in the implementation is that the sourceIsPixmap function returns always false, even if the documentation states that Returns true if the source effectively is a pixmap, e.g., a QGraphicsPixmapItem. I asked the Qt gurus what can be going on here...

The default color is pale yellow, semi-transparent and the border size is set to 1.5. To add the effect simply add this:

 Pixmap *item = new Pixmap(kineticPix);
 HighlightEffect *effect = new HighlightEffect();

 item->setGraphicsEffect( effect );

Here the modified animated tiles example with the effect turned on:


Animated tiles example with QGraphicsPixmapItem highlighting

Hope someone finds this useful.