简体   繁体   中英

How to draw image using QGraphicsItem?

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?

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();
}

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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM