Important: Please read the Qt Code of Conduct -

QPainter won't draw

  • I've got a class "ComponentArea" which is derived from QScrollArea. The ComponentArea has some other QWidget-derivatives in it.
    I modify the palette and enable mouseTracking in the constructor:

    ComponentArea::ComponentArea(QWidget* parent) : QScrollArea(parent)
        QPalette palette = this->palette();
        palette.setColor(QPalette::Base, Qt::white);
        palette.setColor(QPalette::Window, Qt::white);
        palette.setColor(QPalette::AlternateBase, Qt::white);

    The mouseMoveEvent calls repaint(), which triggers the paintEvent:

    void ComponentArea::mouseMoveEvent(QMouseEvent *event)
        if(pressedSocket_first != 0)
            mousePos_global = event->globalPos();
    void ComponentArea::paintEvent(QPaintEvent *event)
        QPainter* painter = new QPainter(this);
        painter->eraseRect(QRect(QPoint(0,0), QPoint(this->size().width(), this->size().height())));
        painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::SquareCap));
        if(pressedSocket_first != 0)
            QPoint socketPos = this->mapFromGlobal(pressedSocket_first->mapToGlobal(QPoint(0,0)));
            socketPos.setX(socketPos.x() + pressedSocket_first->size().width() /2);
            socketPos.setY(socketPos.y() + pressedSocket_first->size().height() /2);
            QPoint mousePos = this->mapFromGlobal(mousePos_global);
            painter->drawLine(socketPos, mousePos);

    The line does not appear. With debugging, I made sure that drawLine() is in fact reached and the values of socketPos and mousePos make sense. Nevertheless the line does not appear. What am I doing wrong? Thanks in advance!

  • Hi and welcome to devnet,

    QPainter paints only when endPaint() is called (the destructor calls endPaint as well).
    I suggest to change your code using a stack variable instead a pointer QPainter painter instead of QPainte *painter also because you never delete created painter

  • @mcosta Hm, neither calling painter->end() manually nor using a "usual" variable solves it. I draw in the ComponentView's children the same way, and it works perfectly.

Log in to reply