[Solved] Drawing a line and image on QGraphicsScene by inheriting from QGraphicsItem

  • Hi,
    I want to draw a LED on a QGraphicsScene (A breadboard). For this I created class LED inheriting from QGraphicsItem

    Here is led.h->
    @#include <QtGui>
    #include <QGraphicsItem>

    class LED : public QGraphicsItem
    explicit LED(QPointF p1, QPointF p2);
    explicit LED(qreal _x1, qreal _y1, qreal _x2, qreal _y2);

    QRectF boundingRect() const;
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
               QWidget *widget);
    static void initLed();

    qreal x1, y1, x2, y2, x, y, w, h;
    static QPixmap *led_on;

    And here is led.cpp->

    @#include "led.h"
    #include "utility.h"
    #include <QtGui>

    QPixmap* LED::led_on;

    LED::LED(QPointF p1, QPointF p2)
    LED(p1.x(), p1.y(), p2.x(), p2.y());

    LED::LED(qreal _x1, qreal _y1, qreal _x2, qreal _y2)
    x1 = _x1; y1 = _y1; x2 = _x2; y2 = _y2;
    x = math::min(x1, x2);
    y = math::min(y1, y2);
    w = math::abs(x1 - x2);
    h = math::abs(y1 - y2);

    QRectF LED::boundingRect() const
    qreal pw = 2;
    return QRectF(x - pw/2, y - pw/2, w + pw, h + pw);

    void LED::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
    QWidget *widget)
    //painter->drawRoundedRect(-10, -10, 20, 20, 5, 5);
    painter->drawLine(x1, y1, x2, y2);
    painter->drawLine(100, 200, 300, 200); //for testing purpose

    void LED::initLed()
    led_on = new QPixmap(":/components/led_on");

    The problem I am facing is:

    1. The values for local variables x1, y1, x2 and y2 are getting changed between Constructor and call to paint function. Like x1 was assigned 19 in Constructor, but inside paint the value became junk (like -1.5830...).

    So the Line (on line 32) is not being drawn (or drawn at random places).

    1. Sometimes even red line (on line 34) does not get drawn immediately.

    The LED is added to the QGraphicsScene by @addItem(new LED(lastMousePos, mousePos));@
    Thanks for any help. This problem has stalled my project for a long time.

  • I have solved the problem. It was rather silly mistake of mine.
    The line @LED(p1.x(), p1.y(), p2.x(), p2.y());@ creates a temporary object with correct x, y etc. values.

    But the object I added to scene remains uninitialized. Hence the junk values.

    The second issue is also simple to see. The boundingRect() function does not always include the red line, so it does not show.

Log in to reply

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