3

我需要使用我的子类绘制图像和几条线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 绘制图像),但决定使用 a 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还是其他的东西?

4

2 回答 2

3

正如错误所暗示的,您必须在创建 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();
}
于 2012-11-05T19:15:47.580 回答
1

这是一个问题,因为 qt 的 gui 类需要一个正在运行的 qapplication,比如...

main(int argc, char* argv[])
{
   QApplication a( argc, argv );

   // your gui class here

   return a.exec();
}

所以你需要构建一个 qt-gui 类,例如一个 qgraphicsview 来显示它

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

于 2012-11-05T19:18:42.113 回答