【问题标题】:read and write QGraphicsScene to a binary file读写 QGraphicsScene 到二进制文件
【发布时间】:2013-08-30 10:46:48
【问题描述】:

在我的应用程序是用 Qt 编写的,我有一个 QGraphicsScene。在这个 QgraphicsScene 中有一个图像和一些用户绘制的项目。我想保存这个 QgraphicsScene,上面有很多东西。

例如我有这个东西:

QGraphicsPixmapItem* image;
QPointF point;
ChromosomeShape::type pointType;
QGraphicsItem *item;

当我将这些保存到文件时,似乎没有问题

但是当我想加载 (datastream >> image;) 时,我收到了一些关于 "no match 'operator >>', qdatastream and QGraphicsPixmapItem*" 的错误

但我不想为 QGraphicsPixmapItem 重载运算符>>,我真的不知道该怎么做。

问:有什么办法可以做到吗?

任何想法都会受到赞赏。

【问题讨论】:

    标签: c++ qt qgraphicsitem qfile


    【解决方案1】:

    从二进制文件读写 QGraphicsScene 不是 Qt 提供的,如果您不习惯使用抽象类和树层次结构进行序列化,那么您自己将非常长且难以完成。This 将是如果你想尝试一下,你最好的朋友。以 QGraphicsScene 为例,你在this situation

    在您的情况下,您可能只想读取/写入您事先知道的 QGraphicsScene 的一小部分,因此可能是可行的。例如,只需像您一样开始尝试读/写QGraphicsPixmapItem。因此,您必须自己实现这两种方法:

    QDataStream &operator<<(QDataStream &, const QGraphicsPixmapItem &);
    QDataStream &operator>>(QDataStream &, QGraphicsPixmapItem &);
    

    那还不存在。当您说“当我将这些保存到文件时,似乎没有问题”时,您可能写的只是您的 QGraphicsPixmapItem 的 地址,即只是一个 32 位或 64 位数字,这是无用的能够再次阅读;-) 更具体地说,您可能做到了:

    datastream << image; // writing a QGraphicsPixmapItem*, useless
    

    代替:

    datastream << *image; // writing a QGraphicsPixmapItem, useful but not provided by Qt
    

    希望这写起来不应该太复杂,因为 Qt 已经提供了 QPixmap 和 QTransform 序列化函数。尝试类似:

    QDataStream &operator<<(QDataStream & out, const QGraphicsPixmapItem & item)
    {
        out << item.transform() << item.pixmap();
        return out;
    }
    
    QDataStream &operator>>(QDataStream & in, QGraphicsPixmapItem & item)
    {
        QTransform t;
        QPixmap p;
        in >> t >> p;
        item.setTransform(t);
        item.setPixmap(p);
        return in;
    }
    

    然后您可以使用以下方式保存QGraphicsPixmapItem *

    datastream << *image;
    

    然后加载它:

    QGraphicsPixmapItem * image = new QGraphicsPixmapItem();
    datastream >> *image;
    

    如果您需要保存QGraphicsPixmapItem 的其他属性(例如isActiveisVisibleacceptDropoffsetshapeModetransformationMode 等...),请继续同样的方式。

    【讨论】:

      猜你喜欢
      • 2012-01-26
      • 2018-07-26
      • 2016-06-14
      • 2021-06-03
      • 2019-04-20
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多