【问题标题】:Incompatible type in custom QGraphicsPixmapItem自定义 QGraphicsPixmapItem 中的类型不兼容
【发布时间】:2016-08-23 01:59:14
【问题描述】:

我有以下代码返回“从不兼容类型 'GraphicsPixmapItem *' 编译器错误分配给 'GraphicsPixmapItem *'。

有人可以帮帮我吗?

代码如下:

主文件:

#include "graphicsscene.h"
#include <QApplication>
#include <QGraphicsView>

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

    GraphicsScene scene;
    scene.setSceneRect(0, 0, 318, 458);
    QGraphicsView view(&scene);
    view.setBackgroundBrush(QPixmap(":/images/background.jpg"));
    view.show();
    return a.exec();
}

自定义 GraphicsScene 标头:

#ifndef GRAPHICSSCENE_H
#define GRAPHICSSCENE_H

#include <QGraphicsScene>

#include "graphicspixmapitem.h"

class GraphicsScene : public QGraphicsScene
{
    Q_OBJECT
public:
    explicit GraphicsScene(QWidget *parent = 0);
    QGraphicsPixmapItem *Logo;
};

#endif // GRAPHICSSCENE_H

自定义GraphicsScene cpp:

#include "graphicsscene.h"

GraphicsScene::GraphicsScene(QWidget *parent) :
    QGraphicsScene()
{
    QPixmap Contactinfo(":/images/ScreenContacts.png");
    GraphicsPixmapItem *buf = new GraphicsPixmapItem;
    buf = addPixmap(Contactinfo);
    buf->setPos(0, 40);
    buf->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemSendsScenePositionChanges);
}

自定义 QGraphicsPixmapItem 标头:

#ifndef GRAPHICSPIXMAPITEM_H
#define GRAPHICSPIXMAPITEM_H

#include <QObject>
#include <QGraphicsPixmapItem>

class GraphicsPixmapItem : public QObject, public QGraphicsPixmapItem
{
    Q_OBJECT
public:
  GraphicsPixmapItem(QGraphicsItem *parent = 0, QGraphicsScene *scene = 0);

protected:
     QVariant itemChange(GraphicsItemChange change, const QVariant &value);
};

#endif // GRAPHICSPIXMAPITEM_H

最后是自定义 QGraphicsPixmapItem cpp:

#include "graphicspixmapitem.h"

GraphicsPixmapItem::GraphicsPixmapItem(QGraphicsItem *parent, QGraphicsScene *scene)
  : QGraphicsPixmapItem(parent, scene)
{
}

#include <QDebug>
QVariant GraphicsPixmapItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
    qDebug() << "itemChange Triggered";
    if (change == ItemPositionChange) {
            qDebug() << "Position changed";
        }
    return QGraphicsItem::itemChange(change, value);
}

【问题讨论】:

    标签: qt qgraphicsitem qgraphicsscene


    【解决方案1】:

    QGraphicsScene::addPixmap() 返回一个 QGraphicsPixmapItem。您正在尝试将指向 QGraphicsPixmapItem 的指针分配给指向不同类型的 GraphicsPixmapItem 的指针。

    还请注意,通过使用 new 分配给 buf,然后调用 QGraphicsScene::addPixmap(),您将创建两个不同的对象,即一个 GraphicsPixmapItem(来自 new)和一个 QGraphicsPixmap(来自 addPixmap)项目。

    您可能想要的是 buf-&gt;setPixmap(Contactinfo); 之类的东西,然后从场景构造函数中调用 addItem(buf);,并消除 addPixmap() 调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 2015-11-09
      • 1970-01-01
      • 2023-02-17
      相关资源
      最近更新 更多