File indexing completed on 2024-12-29 04:11:45
0001 /*************************************************************************** 0002 * * 0003 * Copyright : (C) 2010 The University of Toronto * 0004 * email : netterfield@astro.utoronto.ca * 0005 * * 0006 * This program is free software; you can redistribute it and/or modify * 0007 * it under the terms of the GNU General Public License as published by * 0008 * the Free Software Foundation; either version 2 of the License, or * 0009 * (at your option) any later version. * 0010 * * 0011 ***************************************************************************/ 0012 0013 #ifndef KST_NAMED_PARAMETER 0014 #define KST_NAMED_PARAMETER 0015 0016 #include <QSettings> 0017 #include <QXmlStreamWriter> 0018 #include <QXmlStreamAttributes> 0019 #include <QDomElement> 0020 0021 template<class T, const char* Key, const char* Tag> 0022 class NamedParameter 0023 { 0024 public: 0025 // this is not nice, it sets not the value but its default 0026 NamedParameter(const T& default_value) : 0027 _value(default_value), 0028 _default_value(default_value), 0029 _value_set(false) { 0030 } 0031 0032 void operator>>(QSettings& settings) const { 0033 const QVariant var = QVariant::fromValue<T>(value()); 0034 settings.setValue(Key, var); 0035 } 0036 0037 void operator<<(QSettings& settings) { 0038 const QVariant var = settings.value(Key); 0039 if (!var.isNull()) { 0040 Q_ASSERT(var.canConvert<T>()); 0041 setValue(var.value<T>()); 0042 } 0043 } 0044 0045 void operator>>(QXmlStreamWriter& xml) { 0046 xml.writeAttribute(Tag, QVariant(value()).toString()); 0047 } 0048 0049 void operator<<(QXmlStreamAttributes& att) { 0050 setValue(QVariant(att.value(Tag).toString()).value<T>()); 0051 } 0052 0053 void operator<<(const QDomElement& e) { 0054 if (e.hasAttribute(Tag)) { 0055 setValue(QVariant(e.attribute(Tag)).value<T>()); 0056 } 0057 } 0058 0059 void setValue(const T& t) { 0060 _value = t; 0061 _value_set = true; 0062 } 0063 0064 const T& value() const { 0065 if (!_value_set) { 0066 //qDebug() << "Using unset value " << Key << " using default: " << _default_value; 0067 return _default_value; 0068 } 0069 0070 return _value; 0071 } 0072 0073 operator const T&() const { 0074 return value(); 0075 } 0076 0077 NamedParameter& operator=(const T& t) { 0078 setValue(t); 0079 return *this; 0080 } 0081 0082 bool operator==(const T& rhs) const { 0083 return value() == rhs; 0084 } 0085 0086 bool operator!=(const T& rhs) const { 0087 return !operator==(rhs); 0088 } 0089 0090 private: 0091 T _value; 0092 T _default_value; 0093 bool _value_set; 0094 }; 0095 0096 0097 #endif