c++ - 如何使用 QGraphicsItem 绘制图像?

标签 c++ qt qt4

我需要使用我的子类 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();
}

关于c++ - 如何使用 QGraphicsItem 绘制图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13238130/

相关文章:

c++ - 在 std::erase() 产生未定义行为之前调用 std::fill() 吗?

c++ - 基于文件路径/名称创建 QTreeWidget 目录?

c++ - 带参数的 QT 信号如何工作

c++ - 为什么 QFile::canReadLine() 总是返回 false?

c++ - 在数据库中创建一个新表,并将现有表的描述作为输入

使用 MinGW 的 C++ 可执行文件大小

c++ - 为什么 memset sockaddr_in 为 0

c++ - 如何分配 '-' 等于 ' ' 进行字符串类比较,这可能吗?

mysql - 使用绑定(bind)调用服务器存储过程

qt - 在QT中设置新公共(public)信号后出现段故障