]> vaikene.ee Git - evaf/blob - src/libs/Common/util.cpp
Better handling of boolean types.
[evaf] / src / libs / Common / util.cpp
1 /**
2 * @file Common/util.cpp
3 * @brief Global utility functions for eVaf
4 * @author Enar Vaikene
5 *
6 * Copyright (c) 2011 Enar Vaikene
7 *
8 * This file is part of the eVaf C++ cross-platform application development framework.
9 *
10 * This file can be used under the terms of the GNU General Public License
11 * version 3.0 as published by the Free Software Foundation and appearing in
12 * the file LICENSE included in the packaging of this file. Please review the
13 * the following information to ensure the GNU General Public License version
14 * 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
15 *
16 * Alternatively, this file may be used in accordance with the Commercial License
17 * Agreement provided with the Software.
18 */
19
20 #include "util.h"
21
22 #include <stdio.h>
23
24 //-------------------------------------------------------------------
25
26 QVariant eVaf::Common::toVariant(QString const & value, QVariant const & defaultValue)
27 {
28 // If the default value is not valid, return the string value without conversions
29 if (!defaultValue.isValid())
30 return QVariant(value);
31
32 // Convert to the expected type
33 switch (defaultValue.type()) {
34 case QVariant::UInt: {
35 bool ok;
36 uint v = value.toUInt(&ok, 0);
37 if (ok)
38 return QVariant(v);
39 else
40 return defaultValue;
41 break;
42 }
43 case QVariant::Int: {
44 bool ok;
45 int v = value.toInt(&ok, 0);
46 if (ok)
47 return QVariant(v);
48 else
49 return defaultValue;
50 break;
51 }
52 case QVariant::Double: {
53 bool ok;
54 double v = value.toDouble(&ok);
55 if (ok)
56 return QVariant(v);
57 else
58 return defaultValue;
59 break;
60 }
61 case QVariant::Bool: {
62 if (eVaf::Common::isTrue(value))
63 return QVariant(true);
64 else if (eVaf::Common::isFalse(value))
65 return QVariant(false);
66 else {
67 bool ok;
68 uint v = value.toUInt(&ok, 0);
69 if (ok)
70 return QVariant(v);
71 else
72 return defaultValue;
73 }
74 break;
75 }
76 case QVariant::Char: {
77 if (value.size() > 0) {
78 if (value.startsWith("\\0x")) {
79 bool ok;
80 char c = value.mid(1).toUInt(&ok, 16);
81 if (ok)
82 return QVariant(c);
83 }
84 else if (value.startsWith("\\0")) {
85 bool ok;
86 char c = value.mid(1).toUInt(&ok, 8);
87 if (ok)
88 return QVariant(c);
89 }
90 else
91 return QVariant(value.at(0));
92 }
93 return defaultValue;
94 break;
95 }
96 default:
97 return QVariant(value);
98 }
99 }