Results 1 to 3 of 3

Thread: QVariant::toString and custom data types

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #2
    Join Date
    Jan 2006
    Posts
    128
    Thanked 28 Times in 27 Posts
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default Re: QVariant::toString and custom data types

    Quote Originally Posted by Vladimir View Post
    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:
    Qt Code:
    1. namespace VariantConversion {
    2. QString (*VariantToStringFunction)(const QVariant &);
    3.  
    4. void registerVariantToStringFunction(int usertype,
    5. VariantToStringFunction function);
    6.  
    7. QString variantToString(const QVariant &variant);
    8. }
    To copy to clipboard, switch view to plain text mode 

    Implementation
    Qt Code:
    1. Q_GLOBAL_STATIC(QReadWriteLock, getLock)
    2. typedef QMap<int, VariantConversion::VariantToStringFunction> FunctionMap;
    3. Q_GLOBAL_STATIC(FunctionMap, getFunctionMap)
    4.  
    5. void VariantConversion::registerVariantToStringFunction(int usertype,
    6. VariantToStringFunction function)
    7. {
    8. QWriteLocker writeLock(&getLock());
    9. functionMap[usertype] = function;
    10. }
    11.  
    12. QString VariantConversion::variantToString(const QVariant &variant)
    13. {
    14. int type = variant.userType();
    15. if (type < QVariant::UserType) {
    16. return variant.toString();
    17. }
    18. QReadLocker readLock(&getLock());
    19. if (getFunctionMap().contains(type)) {
    20. return (getFunctionMap()[type])(variant);
    21. }
    22. qDebug("No registered function to convert Variant of type "
    23. "\"%s\" to QString", QMetaType::typeName(type));
    24. return QString();
    25. }
    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
    Last edited by camel; 16th January 2007 at 12:32.

  2. The following user says thank you to camel for this useful post:

    sunil.thaha (17th January 2007)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.