如何使用QGraphicsItem绘制图像?

How to draw image using QGraphicsItem?

本文关键字:图像 绘制 QGraphicsItem 何使用      更新时间:2023-10-16

我需要使用我的子类化QGraphicsItem绘制一个图像和几条线

这是我的代码(头文件)-

#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

注意 -LED将被添加到QGraphicsScene

现在我不知道如何处理它(使用 QGraphicsItem 绘制图像),但决定使用一个static QPixmap,它应该由LED类的所有实例共享。

并在 cpp 文件中添加了这个>

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

但是我在构建和运行时收到此错误-

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

请告诉我该怎么做。(我是Qt的新手) 我应该改用QImage还是其他东西?

正如错误所暗示的那样,您必须在创建 QApplication 后创建 QPixmap。 显然,你的所作所为会导致相反的情况发生。这个问题有很多解决方案,但这个解决方案很干净: 创建初始化 QPixmap 的 LED 类的静态成员:

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

现在像这样设计你的主函数:

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

这是一个问题,因为 qt 的 gui 类需要一个运行 qapp 就像在...

main(int argc, char* argv[])
{
QApplication a( argc, argv );
// your gui class here
return a.exec();
}

所以你需要构建一个Qt-GUI类,例如一个qGraphicsView来显示它

现在,当您有一个图形视图来显示内容时,您需要一个场景来显示并将 QGraphicsItem 添加到场景中......