How do Load/Save Json file in the table (QTableView)?



  • There is a table QTableView 5 lines and 2 columns.

    Trip name and Trip days. I don't want to pee there, I'm like, and I'm all right. I know it's not good to ask without some realisation. )

    How to set up a table with my hands to fill it.

    But it's too soon to explain. I'm asking you to help me turn the labo down, and I don't find any information in the background. Please come and help with this.

    Laboratory work:

    In the annex, let the File menu with Load menu... and Save... which can be downloaded and preserved respectively. Make use of opening and preservation dialogues choosing the target file. May the data be stored in the JSON file. Separate logic on downloading/storage of data into a file Cool.



  • https://github.com/gil9red/table_save_load_as_json ♪ Everything below is in the project repository.

    Since the author of the topic did not indicate the version QtI chose the one I'd be more comfortable writing. Json Total Qt4 No default, but you can. http://habrahabr.ru/post/147952/ Support Library http://qjson.sourceforge.net/ supporting Qt

    Also, the choice of the table model was my choice.

    I'll bring down the window class code and class to keep the / load from Json.


    Window class:

    h:

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    

    #include <QMainWindow>
    #include <QMenu>
    #include <QMenuBar>
    #include <QAction>
    #include <QFileDialog>
    #include <QTableView>
    #include <QStandardItemModel>

    class MainWindow : public QMainWindow
    {
    Q_OBJECT

    public:
    MainWindow(QWidget *parent = 0);

    public slots:
    void load();
    void save();

    private:
    QTableView view;
    QStandardItemModel model;
    };

    #endif // MAINWINDOW_H

    cpp:

    #include "mainwindow.h"
    #include "modelstorage.h"

    MainWindow::MainWindow(QWidget parent) :
    QMainWindow(parent)
    {
    QMenu
    fileMenu = menuBar()->addMenu("&File");
    fileMenu->addAction("Load", this, SLOT(load()));
    fileMenu->addAction("Save", this, SLOT(save()));

    QStringList headers = QStringList() &lt;&lt; "Trip name" &lt;&lt; "Trip days";
    model.setHorizontalHeaderLabels(headers);
    model.setColumnCount(headers.size());
    
    const int rowCount = 5;
    
    for (int row = 0; row &lt; rowCount; row++) {
        QList &lt;QStandardItem *&gt; rowItems;
    
        for (int column = 0; column &lt; model.columnCount(); column++) {
            QStandardItem* item = new QStandardItem(QString("%1_%2x%3").arg(headers[column]).arg(row).arg(column));
            rowItems.append(item);
        }
    
        model.appendRow(rowItems);
    }
    
    view.setModel(&amp;model);
    
    setCentralWidget(&amp;view);
    

    }

    void MainWindow::load()
    {
    QString fileName = QFileDialog::getOpenFileName(this);
    if (fileName.isEmpty()) {
    return;
    }

    ModelStorage::load(fileName, model);
    

    }
    void MainWindow::save()
    {
    QString fileName = QFileDialog::getSaveFileName(this);
    if (fileName.isEmpty()) {
    return;
    }

    ModelStorage::save(fileName, model);
    

    }


    Class for Json:

    h:

    #ifndef MODELSTORAGE_H
    #define MODELSTORAGE_H

    #include <QStandardItemModel>
    #include <QStandardItem>

    #include <QFile>
    #include <QJsonDocument>
    #include <QJsonObject>
    #include <QJsonArray>

    class ModelStorage
    {
    public:
    static bool load(const QString& fileName, QStandardItemModel & model);
    static bool save(const QString& fileName, const QStandardItemModel& model);
    };

    #endif // MODELSTORAGE_H

    cpp:

    #include "modelstorage.h"

    bool ModelStorage::load(const QString& fileName, QStandardItemModel& model) {
    QFile loadFile(fileName);
    if (!loadFile.open(QIODevice::ReadOnly)) {
    qWarning("Couldn't open save file.");
    return false;
    }

    QByteArray saveData = loadFile.readAll();
    QJsonDocument loadDoc = QJsonDocument::fromJson(saveData);
    QJsonObject json = loadDoc.object();
    
    // Очистка модели
    while (model.rowCount() &gt; 0) {
        model.invisibleRootItem()-&gt;removeRow(0);
    }
    
    const int rowCount = json["rowCount"].toInt();
    const int columnCount = json["columnCount"].toInt();
    QJsonArray data = json["data"].toArray();
    
    model.setRowCount(rowCount);
    model.setColumnCount(columnCount);
    
    for (int i = 0; i &lt; rowCount; i++) {
        QJsonArray row = data[i].toArray();
    
        for (int j = 0; j &lt; columnCount; j++) {
            model.setItem(i, j, new QStandardItem(row[j].toString()));
        }
    }
    
    return true;
    

    }

    bool ModelStorage::save(const QString& fileName, const QStandardItemModel& model) {
    QFile saveFile(fileName);
    if (!saveFile.open(QIODevice::WriteOnly)) {
    qWarning("Couldn't open save file.");
    return false;
    }

    QJsonObject json;
    json["rowCount"] = model.rowCount();
    json["columnCount"] = model.columnCount();
    
    QJsonArray data;
    for (int i = 0; i &lt; model.rowCount(); i++) {
        QJsonArray row;
    
        for (int j = 0; j &lt; model.columnCount(); j++) {
            row.append(QJsonValue(model.item(i, j)-&gt;text()));
        }
    
        data.append(row);
    }
    json["data"] = data;
    
    QJsonDocument saveDoc(json);
    saveFile.write(saveDoc.toJson());
    
    return true;
    

    }


    Window and json, describing the table: Скриншот окна и json, описывающий таблицу

    The json structure shall not change with json, but the table row number may also be transmitted to reduce the symptoms of paranoia:




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2