error: C2039: “staticMetaObject”: 不是“QGraphicsItem”的成员

当使用Qt的图形视图框架时,自定义图形类时,一般这样写

class myItem:public QGraphicsItem
{
public:
    myItem();
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
    QRectF boundingRect() const;
};

然而有些时候,我们需要使用信号与槽,就需要增加 Q_OBJECT,这时,就会报错
error: C2039: “staticMetaObject”: 不是“QGraphicsItem”的成员

这时,我们可以这样写,继承QObject

class myItem:public QObject,public QGraphicsItem
{
    Q_OBJECT
 
public:
    myItem();
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
    QRectF boundingRect() const;
};

编译时出现警告 Warning: Class Node implements the interface QGraphicsItem but does not list it in Q_INTERFACES. qobject_cast to QGraphicsItem will not work!

在类的声明(Q_OBJECT下面)中添加:Q_INTERFACES(QGraphicsItem)可解决该问题.