×
Namespaces

Variants
Actions

Clipping using Painter Paths in Qt

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Code ExampleTested with
Devices(s): N8
Compatibility
Platform(s): Symbian
Symbian
Article
Keywords: QPainterPath, QPainter
Created: somnathbanik (19 May 2014)
Last edited: hamishwillee (11 Oct 2012)

This article shows how to cut off QPaintDevice with clipping with the help of a figure, so that it can be seen only inside the boundary of the figure.

ClippingQt.png

Contents

Class Declaration

#ifndef CLIPPINGQT_H
#define CLIPPINGQT_H
#include <QWidget>
namespace Ui {
class ClippingQt;
}
class ClippingQt : public QWidget
{
Q_OBJECT
public:
explicit ClippingQt(QWidget *parent = 0);
~ClippingQt();
private:
Ui::ClippingQt *ui;
public:
virtual void paintEvent(QPaintEvent*);
virtual QSize sizeHint() const {return QSize(200,200);}
};
#endif // CLIPPINGQT_H

In the above code we create a QWidget subclass called ClippingQt. The constructor is empty and the method sizeHint() is just a static method.

Class Implementation

The QPainterPath class can combine instances of all primitive geometry classes into a figure, and it can also include curves. With this technique we have implemented he above figure and the corresponding source code in given below

#include "clippingqt.h"
#include "ui_clippingqt.h"
#include <QtGui>
ClippingQt::ClippingQt(QWidget *parent) :
QWidget(parent),
ui(new Ui::ClippingQt)
{
// ui->setupUi(this);
}
ClippingQt::~ClippingQt()
{
delete ui;
}
void ClippingQt::paintEvent(QPaintEvent* /*ev*/)
{
QLinearGradient gradient(rect().topRight(), rect().bottomLeft());
gradient.setColorAt(0, Qt::red);
gradient.setColorAt(1, Qt::green);
QPainterPath path;
path.cubicTo(rect().topRight(), rect().bottomRight(),
rect().bottomRight());
path.cubicTo(rect().topLeft(), rect().bottomLeft(),
rect().bottomRight());
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing, true);
p.drawTiledPixmap(rect(), QPixmap(":/QtIcon.png"));
p.setBrush(gradient);
p.drawPath(path);
}

In the paintEvent() method we first instantiate a QLinearGradient object, the color gradation of which should run from red to green across the widget. With this gradient we need to fill a Painter Path consisting of two cubic curves. Now we instantiate a QPainter. In the next step we activate anti-aliasing, draw the background, and pass the gradient to the paintbrush. Now when we draw the path it contains the color gradient. Thus elegant figures can also be implemented via Painter paths.

Opaque

To make it opaque replace the line

p.setBrush(gradient);

to

p.setBrush(QColor::fromRgba(qRgba(0,0,0,128)));
p.setCompositionMode(QPainter::CompositionMode_DestinationOut);

Source Code

The full source code presented in this article is available here: File:ClippingQt.zip

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