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
customtypeexample.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3#include <QCoreApplication>
4#include <QDebug>
5#include <QVariant>
6
7//message.h
8
9//! [custom type definition]
11{
12public:
13 Message() = default;
14 ~Message() = default;
15 Message(const Message &) = default;
16 Message &operator=(const Message &) = default;
17
18 Message(const QString &body, const QStringList &headers);
19
22
23private:
24 QString m_body;
25 QStringList m_headers;
26};
27//! [custom type definition]
28
29//! [custom type meta-type declaration]
31//! [custom type meta-type declaration]
32
33//! [custom type streaming operator declaration]
34QDebug operator<<(QDebug dbg, const Message &message);
35//! [custom type streaming operator declaration]
36
37// message.cpp
38
39//! [custom type streaming operator]
40QDebug operator<<(QDebug dbg, const Message &message)
41{
42 QDebugStateSaver saver(dbg);
43 const QList<QStringView> pieces = message.body().split(u"\r\n", Qt::SkipEmptyParts);
44 if (pieces.isEmpty())
45 dbg.nospace() << "Message()";
46 else if (pieces.size() == 1)
47 dbg.nospace() << "Message(" << pieces.first() << ")";
48 else
49 dbg.nospace() << "Message(" << pieces.first() << " ...)";
50 return dbg;
51}
52//! [custom type streaming operator]
53
54//! [getter functions]
56{
57 return m_body;
58}
59
61{
62 return m_headers;
63}
64//! [getter functions]
65
66//main.cpp
67
68int main(int argc, char *argv[])
69{
70 QCoreApplication app(argc, argv);
71 QStringList headers;
72 headers << "Subject: Hello World"
73 << "From: address@example.com";
74 QString body = "This is a test.\r\n";
75 //! [printing a custom type]
76 Message message(body, headers);
77 qDebug() << "Original:" << message;
78 //! [printing a custom type]
79 //! [storing a custom value]
80 QVariant stored;
81 stored.setValue(message);
82 //! [storing a custom value]
83 qDebug() << "Stored:" << stored;
84 //! [retrieving a custom value]
85 Message retrieved = qvariant_cast<Message>(stored);
86 qDebug() << "Retrieved:" << retrieved;
87 retrieved = qvariant_cast<Message>(stored);
88 qDebug() << "Retrieved:" << retrieved;
89 //! [retrieving a custom value]
90 return 0;
91}
[custom type definition]
~Message()=default
Message(const QString &body, const QStringList &headers)
Message & operator=(const Message &)=default
Message(const Message &)=default
Message()=default
QStringList headers() const
QStringView body() const
[custom type streaming operator]
Q_DECLARE_METATYPE(Message)
[custom type definition]
QDebug operator<<(QDebug dbg, const Message &message)
[custom type meta-type declaration]
int main(int argc, char *argv[])
[ctor_close]