简体   繁体   English

如何使用QGraphicsItem绘制图像?

[英]How to draw image using QGraphicsItem?

I need to draw an Image and a couple of lines, using my sub-classed QGraphicsItem 我需要使用我的子类QGraphicsItem绘制一个Image和几行

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 注意 - LED将添加到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. 现在我不知道如何处理它(使用QGraphicsItem绘制图像),但决定使用static QPixmap ,它将由LED类的所有实例共享。

And in cpp file added this-> 并在cpp文件中添加了这个 - >

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? (我是Qt的新手)我应该使用QImage或其他东西吗?

As the error suggests, you must create the QPixmap after the QApplication has been created. 如错误所示,您必须在创建QApplication后创建QPixmap。 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: 这个问题有很多解决方案,但是这个问题非常简洁:创建一个初始化QPixmap的LED类的静态成员:

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 ... 这是一个问题,导致qt的gui类需要像...一样运行qapplication ...

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 所以你需要建立一个qt-gui类,例如qgraphicsview来显示它

now when you have a graphicsview to display the content you need a scene to display and add the qgraphicsitem to the scene ... 现在当你有一个显示内容的图形视图时,你需要一个场景来显示并将qgraphicsitem添加到场景中......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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