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:
    !http://imgbin.org/images/12066.png(example)!

    !http://imgbin.org/images/12067.png(example2)!

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

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

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

    DrawLabel dl;
    dl.resize(60,100);
    dl.show();

    return a.exec();
    }@

    DrawLabel.h
    @#ifndef DRAWLABEL_H
    #define DRAWLABEL_H

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

    class DrawLabel : public QLabel
    {
    Q_OBJECT

    public:
    DrawLabel(QWidget *parent = 0);

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

    private:
    int depth;
    };

    #endif@

    DrawLabel.cpp
    @#include <iostream>

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

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

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

    // Draw a triangle
    painter.setPen(QPen(Qt::black));
    painter.drawLine(10, 10, 50, 10);
    painter.drawLine(10, 10, 30, 10+depth);
    painter.setPen(QPen(Qt::red));
    painter.drawLine(30, 10+depth, 50, 10);
    }

    void DrawLabel::keyPressEvent(QKeyEvent *event)
    {
    switch(event->key())
    {
    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";

    update();
    }@

    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:
    https://bugreports.qt-project.org/browse/QTBUG-26013
    https://bugreports.qt-project.org/browse/QTBUG-25896
    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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.