Originally Posted by
Vladimir
Something like toString but which can handle user-defined types ?
Not very nice, but you could do something like this:
(insert Pseudo-code/compile on own risk disclaimer here ;-)
Header:
namespace VariantConversion {
void registerVariantToStringFunction(int usertype,
VariantToStringFunction function);
}
namespace VariantConversion {
QString (*VariantToStringFunction)(const QVariant &);
void registerVariantToStringFunction(int usertype,
VariantToStringFunction function);
QString variantToString(const QVariant &variant);
}
To copy to clipboard, switch view to plain text mode
Implementation
typedef QMap<int, VariantConversion::VariantToStringFunction> FunctionMap;
Q_GLOBAL_STATIC(FunctionMap, getFunctionMap)
void VariantConversion::registerVariantToStringFunction(int usertype,
VariantToStringFunction function)
{
functionMap[usertype] = function;
}
{
int type = variant.userType();
return variant.toString();
}
if (getFunctionMap().contains(type)) {
return (getFunctionMap()[type])(variant);
}
qDebug("No registered function to convert Variant of type "
"\"%s\" to QString",
QMetaType::typeName(type
));
}
Q_GLOBAL_STATIC(QReadWriteLock, getLock)
typedef QMap<int, VariantConversion::VariantToStringFunction> FunctionMap;
Q_GLOBAL_STATIC(FunctionMap, getFunctionMap)
void VariantConversion::registerVariantToStringFunction(int usertype,
VariantToStringFunction function)
{
QWriteLocker writeLock(&getLock());
functionMap[usertype] = function;
}
QString VariantConversion::variantToString(const QVariant &variant)
{
int type = variant.userType();
if (type < QVariant::UserType) {
return variant.toString();
}
QReadLocker readLock(&getLock());
if (getFunctionMap().contains(type)) {
return (getFunctionMap()[type])(variant);
}
qDebug("No registered function to convert Variant of type "
"\"%s\" to QString", QMetaType::typeName(type));
return QString();
}
To copy to clipboard, switch view to plain text mode
EDIT: I thought about it more, and having a lock in a static variable inside of a function is not the greatest idea, and kind of braindead, at least in older compilers.... (Look up thread safety of static variables)
I do not think Q_GLOBAL_STATIC is public API at this point, but you can find information about it on the web:
http://delta.affinix.com/2006/01/31/q_global_static/
http://article.gmane.org/gmane.comp....vel.core/39118
Bookmarks