"QPainter::drawRects: Painter not active " error C++/QT
<p>I'm a beginner at Qt
 and c++ and I wanted to see how to use a QPainter and events in Qt but I got stuck because of an error message during the execution, my original code:</p>

<p>the main.cpp</p>

<pre><code>#include "customwidget.h"
#include &lt;QApplication&gt;

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QScopedPointer&lt;QWidget&gt; widget(new customWidget());
    widget-&gt;resize(240, 120);
    widget-&gt;show();

    return a.exec();
}
</code></pre>

<p>and the header:</p>

<pre><code>#ifndef CUSTOMWIDGET_H
#define CUSTOMWIDGET_H

#include &lt;QWidget&gt;
#include &lt;QMouseEvent&gt;
#include &lt;QPoint&gt;
#include &lt;QPainter&gt;

class customWidget : public QWidget
{
    Q_OBJECT
public:
    explicit customWidget(QWidget *parent = 0);
    void paintEvent(QPaintEvent *);
    void mouseMoveEvent(QMouseEvent *event);
    void mousePressEvent(QMouseEvent *event);

private:
    QPoint m_mousePos;
    QRect m_r2;
signals:

    void needToRepaint();
public slots:
};

#endif // CUSTOMWIDGET_H
</code></pre>

<p>and the .cpp:</p>

<pre><code>#include "customwidget.h"

customWidget::customWidget(QWidget *parent) : QWidget(parent)
{
    QRect m_r2;
    QPoint m_mousePos;

    QObject::connect(this, SIGNAL(needToRepaint()), this, SLOT(repaint()));
}

void customWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

// ############ First Rectangle ****************************************

    QRect r1 = rect().adjusted(10, 10, -10, -10);
    painter.setPen(QColor("#FFFFFF"));
    painter.drawRect(r1);

// ############ Seconde Rectangle ****************************************

    QRect r2(QPoint(0, 0), QSize(100, 100));


    m_r2.moveCenter(m_mousePos);

    QPainter painter2;
    QPen pen;
    painter2.setPen(QColor("#000000"));
    pen.setWidth(3);
    painter2.setPen(pen);
    painter2.drawRect(m_r2);
    update();



}

void customWidget::mouseMoveEvent(QMouseEvent *event)
{

    m_mousePos = event-&gt;pos();

    emit needToRepaint();
}
</code></pre>

<p>I tried to search it on the web and saw that it's because the QPainter isn't located in the paintEvent but it's not the case in my code, thanks for your help.</p>