Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
registerConverters.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4#include <QJsonObject>
5#include <QMetaType>
6#include <QString>
7
8using namespace Qt::StringLiterals;
9
10int main() {
11 //! [member]
12 struct Coordinates {
13 int x;
14 int y;
15 int z;
16
17 QString toString() const { return u"[x: %1; y: %2, z: %3]"_s.arg(QString::number(x),
18 QString::number(y),
19 QString::number(z)); }
20 };
21 QMetaType::registerConverter<Coordinates, QString>(&Coordinates::toString);
22 //! [member]
23
24 //! [memberOk]
25 struct BigNumber {
26 long long l;
27
28 int toInt(bool *ok = nullptr) const {
29 const bool canConvertSafely = l < std::numeric_limits<int>::max();
30 if (ok)
31 *ok = canConvertSafely;
32 return l;
33 }
34 };
35 QMetaType::registerConverter<BigNumber, int>(&BigNumber::toInt);
36 //! [memberOk]
37
38 //! [implicit]
39 class Counter {
40 int number = 0;
41 public:
42 int value() const { return number; }
43 operator int() const { return value(); }
44 void increment() {++number;}
45 };
46 QMetaType::registerConverter<Counter, int>();
47 //! [implicit]
48
49 struct CustomStringType {
50 const char *data() const {return nullptr;}
51 };
52
53 struct CustomPointType{
54 double x;
55 double y;
56 };
57
58 //! [unaryfunc]
59 QMetaType::registerConverter<CustomStringType, QString>([](const CustomStringType &str) {
60 return QString::fromUtf8(str.data());
61 });
62 QMetaType::registerConverter<QJsonValue, CustomPointType>(
63 [](const QJsonValue &value) -> std::optional<CustomPointType> {
64 const auto object = value.toObject();
65 if (!object.contains("x") || !object.contains("y"))
66 return std::nullopt; // The conversion fails if the required properties are missing
67 return CustomPointType{object["x"].toDouble(), object["y"].toDouble()};
68 });
69 //! [unaryfunc]
70}
int main()
[open]