我需要使用我的子类 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/