Painting On WIdgets

The following are two examples for painting on custom widgets.

First, a simple rect widget with custom paint event, and then the famous artistic widget which draws rotated rectangles:

#ifndef MYRECT_H
#define MYRECT_H

#include <QWidget>

class MyRect : public QWidget
{
    Q_OBJECT
public:
    explicit MyRect(QWidget *parent = 0);

    virtual void paintEvent(QPaintEvent *);

};

#endif // MYRECT_H
#include "myrect.h"
#include <QPainter>
#include <QDebug>

MyRect::MyRect(QWidget *parent) :
    QWidget(parent)
{
}

void MyRect::paintEvent(QPaintEvent *)
{
    qDebug() << "Paint !";
    QPainter painter(this);

    QPen pen = painter.pen();
    pen.setWidth(10);

    QColor bgColor = palette().color(QPalette::Window);
    pen.setBrush(Brush(bgColor));

    QColor kool(0, 0, 0, 200);
    painter.setPen(pen);
    painter.setBrush(kool);

    painter.drawRect(0, 0, rect().width(), rect().height());
}


#ifndef ARTISTICWIDGET_H
#define ARTISTICWIDGET_H

#include <QWidget>

class ArtisticWidget : public QWidget
{
    Q_OBJECT
public:
    explicit ArtisticWidget(QWidget *parent = 0);

    virtual void paintEvent(QPaintEvent *);

};

#endif // ARTISTICWIDGET_H

#include "artisticwidget.h"
#include <QPaintEvent>
#include <QPainter>

ArtisticWidget::ArtisticWidget(QWidget *parent) :
    QWidget(parent)
{
}

void ArtisticWidget::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e);
    QPainter p(this);

    QList<QColor> colors;
    colors << Qt::red << Qt::blue << Qt::green << Qt::yellow << Qt::magenta;

    qreal width = rect().width();
    qreal height = rect().height();

    for ( int i=0; i < width; i += 10 )
    {
        int colorIdx = (i / 10) % colors.length();
        p.setBrush(QBrush(colors.at(colorIdx)));

        p.rotate((width - i) / 10);
        p.drawRect(0, 0, width - i, height - i);
    }
}