Save/Load items from a QGraphicsScene

喜欢而已 提交于 2019-12-06 11:24:58

问题


I want to save all items in a QGraphicsScene to a file. When I load the file, I should be able to use them as QGraphicsItems(as before). I keep my items in a QList like QList of QGraphicsItems that i called mItemsOnScreen. I should be able to get back that list when i load the file.How can I save those items to a file on disk. What kind of a file format should i use? And of course how will i read that file back?Please Some Help...And Thank's in advance.

I already do this but it save image format:

void MainWindow::loadImage(){ QString fichier = QFileDialog::getOpenFileName(this,
                                                tr("Open Image"), "C:/", tr("Image Files (*.png *.jpg *.bmp)"));

    if(fichier != "")
    {
        //QGraphicsView *vue = new QGraphicsView(scene);
        QPixmap monPixmap(fichier);
        scene->addPixmap(monPixmap);
        if(monPixmap.load(fichier))
            QMessageBox::information(0,"Chargement réussi","Le Diagrame a bien été chargé !");
        else
            QMessageBox::critical(0,"Erreur de Chargement","Le Chargement du Diagrame a échoué !");
    } }

回答1:


Here is how I would do this. This code only represents general logic and you may have to edit it to make it work.

QVariant item_to_variant(QGraphicsItem* item) {
  QVariantHash data;
  //save all needed attributes
  data["pos"] = item->pos();
  data["rotation"] = item->rotation();
  if(QGraphicsPixmapItem* pixmap_item = dynamic_cast<QGraphicsPixmapItem*>(item)) {
    data["type"] = "pixmap";
    data["pixmap"] = pixmap_item->pixmap();
  } else { /*...*/ }
 //...
  return data;
}

QGraphicsItem* item_from_variant(QVariant v) {
  QVariantHash data = v.toHash();
  QGraphicsItem* result;
  if (data["type"].toString() == "pixmap") {
    result = new QGraphicsPixmapItem();
    result->setPixmap(data["pixmap"].value<QPixmap>());
  } else { /*...*/ }
  result->setPos(data["pos"].toPointf());
  result->setRotation(data["rotation"].toDouble());
  //...
  return result;
}

void save_state() {
  QVariantList data_list;
  foreach(QGraphicsItem* item, items_list) {
    data_list << item_to_variant(item);
  }
  QSettings settings;
  settings.setValue("items", data_list);
}

void restore_state() {
  QSettings settings;
  foreach(QVariant data, settings.value("items").toList()) {
    QGraphicsItem* item = item_from_variant(data);
    scene->addItem(item);
    items_list << item;
  }

}


来源:https://stackoverflow.com/questions/30678877/save-load-items-from-a-qgraphicsscene

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!