3
votes

I need to draw an Image and a couple of lines, using my sub-classed QGraphicsItem

Here is my code(header file)-

#ifndef LED_H
#define LED_H

#include <QtGui>
#include <QGraphicsItem>

class LED : public QGraphicsItem
{
public:
    explicit LED();

    QRectF boundingRect() const;

    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
               QWidget *widget);

private:
    static QPixmap *led_on; //<--Problem
};

#endif // LED_H

Note- LED will be added to QGraphicsScene

Now I don't know how to approach it(drawing image using QGraphicsItem), but decided to use a static QPixmap, which shall be shared by all the instances of LED class.

And in cpp file added this->

QPixmap* LED::led_on = new QPixmap(":/path");

But I am getting this error on build and run-

QPixmap: Cannot create a QPixmap when no GUI is being used
QPixmap: Must construct a QApplication before a QPaintDevice
The program has unexpectedly finished.

Please tell me how to do it. (I am new to Qt) Should I use QImage or something else instead?

2
Side note: since QGraphicsItem does not inherit from QObject, you can't use signals or slots. So you should remove the "signals:" and "public slots:" macros.Anthony
@Anthony: Oh right! QtCreator added it automatically, I will remove it.Vinayak Garg

2 Answers

3
votes

As the error suggests, you must create the QPixmap after the QApplication has been created. Apparently what you've done causes the opposite to occur. There are numerous solutions to this problem, but this one is pretty clean: Create a static member of your LED class that initializes the QPixmap:

void LED::initializePixmap() // static
{
    led_on = new QPixmap(":/path");
}

Now design your main function like this:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv); // first construct the QApplication

    LED::initializePixmap(); // now it is safe to initialize the QPixmap

    MainWindow w; // or whatever you're using...
    w.show();

    return a.exec();
}
1
votes

this is a problem, cause the gui classes of qt need a running qapplication like in ...

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

   // your gui class here

   return a.exec();
}

so you need to build a qt-gui class and for example a qgraphicsview to display it

now when you have a graphicsview to display the content you need a scene to display and add the qgraphicsitem to the scene ...