qt6windows7/examples/corelib/serialization/savegame/character.cpp

84 lines
1.7 KiB
C++
Raw Normal View History

2023-10-30 06:33:08 +08:00
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "character.h"
#include <QMetaEnum>
#include <QTextStream>
2023-11-02 01:02:52 +08:00
Character::Character() = default;
Character::Character(const QString &name, int level, Character::ClassType classType)
: mName(name), mLevel(level), mClassType(classType)
2023-10-30 06:33:08 +08:00
{
}
QString Character::name() const
{
return mName;
}
void Character::setName(const QString &name)
{
mName = name;
}
int Character::level() const
{
return mLevel;
}
void Character::setLevel(int level)
{
mLevel = level;
}
Character::ClassType Character::classType() const
{
return mClassType;
}
void Character::setClassType(Character::ClassType classType)
{
mClassType = classType;
}
2023-11-02 01:02:52 +08:00
//! [fromJson]
Character Character::fromJson(const QJsonObject &json)
2023-10-30 06:33:08 +08:00
{
2023-11-02 01:02:52 +08:00
Character result;
if (const QJsonValue v = json["name"]; v.isString())
result.mName = v.toString();
if (const QJsonValue v = json["level"]; v.isDouble())
result.mLevel = v.toInt();
2023-10-30 06:33:08 +08:00
2023-11-02 01:02:52 +08:00
if (const QJsonValue v = json["classType"]; v.isDouble())
result.mClassType = ClassType(v.toInt());
2023-10-30 06:33:08 +08:00
2023-11-02 01:02:52 +08:00
return result;
2023-10-30 06:33:08 +08:00
}
2023-11-02 01:02:52 +08:00
//! [fromJson]
2023-10-30 06:33:08 +08:00
2023-11-02 01:02:52 +08:00
//! [toJson]
QJsonObject Character::toJson() const
2023-10-30 06:33:08 +08:00
{
2023-11-02 01:02:52 +08:00
QJsonObject json;
2023-10-30 06:33:08 +08:00
json["name"] = mName;
json["level"] = mLevel;
json["classType"] = mClassType;
2023-11-02 01:02:52 +08:00
return json;
2023-10-30 06:33:08 +08:00
}
2023-11-02 01:02:52 +08:00
//! [toJson]
2023-10-30 06:33:08 +08:00
2023-11-02 01:02:52 +08:00
void Character::print(QTextStream &s, int indentation) const
2023-10-30 06:33:08 +08:00
{
const QString indent(indentation * 2, ' ');
2023-11-02 01:02:52 +08:00
const QString className = QMetaEnum::fromType<ClassType>().valueToKey(mClassType);
2023-10-30 06:33:08 +08:00
2023-11-02 01:02:52 +08:00
s << indent << "Name:\t" << mName << "\n"
<< indent << "Level:\t" << mLevel << "\n"
<< indent << "Class:\t" << className << "\n";
2023-10-30 06:33:08 +08:00
}