Qt World Summit: Register Today!

repaint doesn't call paintEvent

  • I am trying to write a Paint like program and for a start i just want to draw simple rectangles.So I Inherited from QGraphicsView . The Idea is to just click on Canvas drag the mouse and draw a rect. But repaint() in mouseMoveEvent doesn't call/trigger paintEvent. I also checked viewports paintEvent and that doesn't get called either.

    Qt version : 5.7.1
    OS : Windows 7

    class Canvas : public QGraphicsView {
        Canvas(QWidget* parent = 0);
        void mousePressEvent(QMouseEvent* e) override;
        void mouseMoveEvent(QMouseEvent* e) override;
        void paintEvent(QPaintEvent* e) override;
        QPointF firstPoint_;
        QPointF secondPoint_;
    Canvas::Canvas(QWidget* parent ) : QGraphicsView(parent),m_drawingRectangle(false) ,m_currentColor(Qt::red){
        customViewport_ = new CustomViewport(this);
    void Canvas::mousePressEvent(QMouseEvent* e) {
        switch (e->button()) {
            case Qt::LeftButton: {
                firstPoint_ = mapToScene(e->pos());
    void Canvas::mouseMoveEvent(QMouseEvent* e) {
        secondPoint_ = mapToScene(e->pos());
    void Canvas::paintEvent(QPaintEvent* e){
        QPainter painter(viewport());    //I have also tried with QPainter(this)

  • Lifetime Qt Champion

    @DrZod How did you check that paintEvent() is not called?
    Also, did you try update() instead of repaint()?

  • @DrZod said in repaint doesn't call paintEvent:

    mouseMoveEvent doesn't call/trigger paintEvent.

    Maybe a silly question, but are you sure the item is visible?
    And, as written in documentation, it is better to use update() instead of repaint() to avoid possible recursive calls:

    Warning: If you call repaint() in a function which may itself be called from paintEvent(), you may get infinite recursion. The update() function never causes recursion.

  • Moderators

    From what I understand from the Documentation, you're not supposed to do your manual painting on a QGraphicsView from the paint event, but rather use the drawForeground method.

    I also found this old topic:
    should still be relevant for your case.

  • @jsulm I put a breakpoint in my paintEvent implementation.
    I have tried both of them,neither one triggers paintEvent

  • @KroMignon What item are you referring? and to answer your question yes I have tried update().

  • @DrZod I am not aware about QGraphicsView, but I think your Canvas class should sub-class QGraphicsItem. I don't be sure it made sense to sub-class QGraphicsView... But I am not a specialist in this domaine.

Log in to reply