Please nominate your Qt Champions for 2021!

Can't get QPainter to draw a simple triangle

  • I can't get QPainter to draw a simple triangle. The example below shows the side marked red doesn't line up at either end. You will need to zoom to see clearly. (Qt 5.0.1, MacOS X 10.8.2)

    Some examples:

    @QT += widgets
    TEMPLATE = app
    HEADERS = DrawLabel.h
    SOURCES = main.cpp DrawLabel.cpp@

    @#include <QApplication>
    #include "DrawLabel.h"

    int main(int argc, char *argv[])
    QApplication a(argc, argv);

    DrawLabel dl;

    return a.exec();

    @#ifndef DRAWLABEL_H
    #define DRAWLABEL_H

    #include <QLabel>
    #include <QPaintEvent>
    #include <QKeyEvent>

    class DrawLabel : public QLabel

    DrawLabel(QWidget *parent = 0);

    void paintEvent(QPaintEvent *event);
    void keyPressEvent(QKeyEvent *event);

    int depth;


    @#include <iostream>

    #include <QPen>
    #include "DrawLabel.h"

    DrawLabel::DrawLabel(QWidget* parent) :
    QLabel(parent), depth(10)
    { }

    void DrawLabel::paintEvent(QPaintEvent *event)
    QPainter painter(this);

    // Draw a triangle
    painter.drawLine(10, 10, 50, 10);
    painter.drawLine(10, 10, 30, 10+depth);
    painter.drawLine(30, 10+depth, 50, 10);

    void DrawLabel::keyPressEvent(QKeyEvent *event)
    case Qt::Key_Up: depth++; break;
    case Qt::Key_Down: depth--; break;
    case Qt::Key_Escape: depth = 10; break;

    std::cerr << "Depth now: " << depth << "\n";


    Edit: inlined the images for you; Andre

  • Seems this is a Mac issue, on Windows your code works as it should.

  • the DrawLabel.cpp is miss #include<QPainter>bq.

  • @calleric

    It makes no difference on Mac.

  • Unfortunately, QPainter has been very broken since Qt 4.8, see the following bug reports:
    and many more related ones.
    While the Qt developers have tried to fix this regression (after all, QPainter was working back in Qt4.7), they couldn't properly fix it until today.
    I assume QPainter is just a deprecated class, in favor of the new QML for mobile consumer devices. So Desktop application writers who use QPainter need to stick with Qt 4.7, as this QPainter bug makes all newer versions unusable.

  • That's a shame. I had some similar problems when I was on 4.7.4 but it got worse when I moved to 5.

Log in to reply