c++ - 序列化形状以保存并重新绘制

标签 c++ qt qdatastream

我有一个 QGraphicsScene,我正在其中绘制 QPainterPath,我需要能够保存形状,并在应用程序再次运行时重新绘制它。这是我绘制形状的方式、简化版本和我的书写方法。

void drawPath(){
    QPoint p1 = QPoint(10, 20);
    writePointsToFile(p1);
    QPoint p2 = QPoint(25, 30);
    writePointsToFile(p2);
    QPoint p3 = QPoint(40, 60);
    writePointsToFile(p3);

    QPainterPath path;
    path.moveTo(p1.x(), p1.y());
    path.lineTo(p2.x(), p2.y());
    path.lineTo(p3.x(), p3.y());
}

void writePointsToFile(QPoint point){
    QFile file("../path.dat");
    file.open(QIODevice::WriteOnly);
    QDataStream out(&file);
    out << point;
    file.close();
}

目前,我的文件在运行时从未被写入。

但除此之外,序列化此数据以便我可以重建形状的正确方法是什么?

我以为我可以处理重新绘制,但我对序列化的理解不够透彻。

我要序列化这些点吗? 包含点的列表?

我的想法是,如果我序列化这些点,当我反序列化时,我然后将它们添加到一个列表中,我应该能够根据列表中每个点的位置重新创建形状;也就是说,位置 0 的点是 p1,位置 1 的点是 p2,等等。但我无法做到这一点,因为无论如何都没有向文件写入任何内容。另外,我一开始并不完全确定数据序列化会带来什么。

在这方面的任何帮助都会很棒。

编辑:根据反馈,我现在正在我的 write 方法中尝试这样做

QFile file("../path.dat");
file.open(QIODevice::WriteOnly);
QDataStream out(&file);
QDataStream & operator << (QDataStream& file, const QPainterPath& path);
out << path;
file.close();

这编译得很好,尽管我不完全确定我这样做是对的,但没有任何内容被写入文件,所以我假设我仍然在某个地方。

最佳答案

Qt 已经提供了直接序列化和反序列化 QPainterPath 所必需的运算符:

QDataStream &   operator<<(QDataStream & stream, const QPainterPath & path)
QDataStream &   operator>>(QDataStream & stream, QPainterPath & path)

所以不需要序列化点,当你可以序列化路径的确切内容时,包括复杂的多组件路径。

所以你应该将路径实现为一个持久化成员变量,这样你就可以从文件中读取它或将它写入文件,并且在 draw 方法中你只需绘制路径。

Currently, my file is never written to when it runs.

我敢打赌,因为永远不会调用 writePointsToFile()。当您尝试打开文件等时,您可能还会养成检查错误的好习惯。您也没有指定 QIODevice::Append,因此即使您确实写入了磁盘,您也只会写入一个点,每次都会覆盖前一个点。

编辑:根据您的编辑,您似乎已经超前了,在急于使用它之前仍然需要学习基本的 C++。尝试这样的事情,并找出你哪里出错了:

QPoint p1 = QPoint(10, 20);
QPoint p2 = QPoint(25, 30);
QPoint p3 = QPoint(40, 60);

QPainterPath path;
path.moveTo(p1.x(), p1.y());
path.lineTo(p2.x(), p2.y());
path.lineTo(p3.x(), p3.y());

QFile file("../path.dat");
if (!file.open(QIODevice::WriteOnly)) return;
QDataStream out(&file);
out << path;

关于c++ - 序列化形状以保存并重新绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43456953/

相关文章:

c++ - VS Code "step into"调试器配置

c++ - 如果第一次失败,重新尝试内存分配?

c++ - 'QOAuth::Interface& QOAuth::Interface::operator=(const QOAuth::Interface&)' 是私有(private)的

c++ - (反)序列化枚举类

c++ - 如何知道 QDataStream 不能反序列化某些东西?

qt - 如何将 QAbstractItemModel 序列化为 QDataStream?

c++ - 在 windows7 : "no such file or directory" 上使用 mingw32 编译 Qt 4.8.5

c++ - 从 vector 中删除已完成的线程

c++ - QFileDialog:选择文件后添加后缀

c++ - app.exec() 无法调用其他方法(静态库 Qt)