nprogram’s blog

気ままに、プログラミングのトピックについて書いていきます

QSettingsクラスに、ユーザー定義クラス(独自クラス)の情報を格納する・読み出す方法について [Qt]

作成環境について

Qt Creator 4.3.1で、以下の設定で、プロジェクトを作成しております。以下の設定でクラス名、cppファイル名、hファイル名はすべてデフォルトを使用しています。

  • Qtウィジェットアプリケーション
  • 基底クラスは、QMainWindows
  • フォームを生成する

コードについて

ユーザー定義クラスとして、Paintクラスを作成しました。Paintクラスの記載[paint.cpp][paint.h]は、直前の記事から変更ありません。

[main.cpp]

#include "mainwindow.h"
#include <QApplication>
#include <QSettings>
#include <iostream>
#include <string>

int main(int argc, char *argv[])
{
    qRegisterMetaTypeStreamOperators<Paint>("Paint");
    QSettings settings("Organization", "Application");

    Paint paint("Picaso", 1932);

    // Write
    settings.setValue("custom", QVariant::fromValue(paint));

    // Read
    QVariant vInfo = settings.value("custom", QVariant());
    Paint pInfo = vInfo.value<Paint>();
    
    // Debug表示
    std::cout << "title : " << pInfo._title.toStdString() << std::endl << "year : " << pInfo._year << std::endl;

    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

実行結果

f:id:nprogram:20170806232106p:plain

  • 以下のサイトを参考にさせていただきました。ありがとうございます。
    • QSettingsでアプリケーションの設定を保存したい

taurano.hatenablog.com