qt6windows7/examples/corelib/serialization/convert/textconverter.cpp

100 lines
2.3 KiB
C++
Raw Normal View History

2023-10-30 06:33:08 +08:00
// Copyright (C) 2018 Intel Corporation.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
#include "textconverter.h"
#include <QFile>
#include <QTextStream>
2023-11-02 01:02:52 +08:00
using namespace Qt::StringLiterals;
2023-10-30 06:33:08 +08:00
static void dumpVariant(QTextStream &out, const QVariant &v)
{
switch (v.userType()) {
case QMetaType::QVariantList: {
const QVariantList list = v.toList();
for (const QVariant &item : list)
dumpVariant(out, item);
break;
}
case QMetaType::QString: {
const QStringList list = v.toStringList();
for (const QString &s : list)
out << s << Qt::endl;
break;
}
case QMetaType::QVariantMap: {
const QVariantMap map = v.toMap();
for (auto it = map.begin(); it != map.end(); ++it) {
out << it.key() << " => ";
dumpVariant(out, it.value());
}
break;
}
case QMetaType::Nullptr:
out << "(null)" << Qt::endl;
break;
default:
out << v.toString() << Qt::endl;
break;
}
}
2023-11-02 01:02:52 +08:00
QString TextConverter::name() const
2023-10-30 06:33:08 +08:00
{
2023-11-02 01:02:52 +08:00
return "text"_L1;
2023-10-30 06:33:08 +08:00
}
2023-11-02 01:02:52 +08:00
Converter::Directions TextConverter::directions() const
2023-10-30 06:33:08 +08:00
{
2023-11-02 01:02:52 +08:00
return Direction::InOut;
2023-10-30 06:33:08 +08:00
}
2023-11-02 01:02:52 +08:00
bool TextConverter::probeFile(QIODevice *f) const
2023-10-30 06:33:08 +08:00
{
if (QFile *file = qobject_cast<QFile *>(f))
2023-11-02 01:02:52 +08:00
return file->fileName().endsWith(".txt"_L1);
2023-10-30 06:33:08 +08:00
return false;
}
2023-11-02 01:02:52 +08:00
QVariant TextConverter::loadFile(QIODevice *f, const Converter *&outputConverter) const
2023-10-30 06:33:08 +08:00
{
if (!outputConverter)
outputConverter = this;
QVariantList list;
QTextStream in(f);
2023-11-02 01:02:52 +08:00
QString line;
2023-10-30 06:33:08 +08:00
while (!in.atEnd()) {
in.readLineInto(&line);
bool ok;
2023-11-02 01:02:52 +08:00
if (qint64 v = line.toLongLong(&ok); ok)
list.append(v);
else if (double d = line.toDouble(&ok); ok)
2023-10-30 06:33:08 +08:00
list.append(d);
2023-11-02 01:02:52 +08:00
else
list.append(line);
2023-10-30 06:33:08 +08:00
}
return list;
}
2023-11-02 01:02:52 +08:00
void TextConverter::saveFile(QIODevice *f, const QVariant &contents,
const QStringList &options) const
2023-10-30 06:33:08 +08:00
{
if (!options.isEmpty()) {
2023-12-05 01:42:35 +08:00
qFatal("Unknown option '%s' to text output. This format has no options.",
qPrintable(options.first()));
2023-10-30 06:33:08 +08:00
}
QTextStream out(f);
dumpVariant(out, contents);
}
static TextConverter textConverter;