Clipping using Painter Paths in Qt
Article Metadata
Code Example
Tested with
Compatibility
Article
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.
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
Source Code
The full source code presented in this article is available here: File:ClippingQt.zip

