FreddyKay
FreddyKay

Reputation: 285

Convert QStrings to other types

I want to convert QStrings to different types. I would like to do this as generically and easy as possible without having to write an explicit method for each type.

I thought of using a template function, something like this:

template<typename T>
void getValueFromString(QString str, T& returnVal)
{
    returnVal = static_cast<T>(str);
}

Obviously this doesn't work, but something like that I would like to have.

Is there an easy way to do that?

Upvotes: 1

Views: 2768

Answers (4)

masoud
masoud

Reputation: 56479

QString has lots of convert methods and you probably don't need your new function, for example:

QString str = "FF";
bool ok;
int hex = str.toInt(&ok, 16);       // hex == 255, ok == true
int dec = str.toInt(&ok, 10);       // dec == 0, ok == false

I'm not sure it's OK to inherit from QString or not, but you can make a child from it and override casts. You can override cast of a class, for example:

class Circle
{
public:
    Circle(int radius) : radius(radius) {}
    operator int() const { return radius; } 
private:
    int radius;
};

int x = static_cast<int>(aCircle);

Again, overriding static_cast for QString doesn't look logical.

Upvotes: 4

manlio
manlio

Reputation: 18902

If Boost is an option you could write:

#include <boost/lexical_cast.hpp>

template<typename T>
void getValueFromString(QString str, T& returnVal)
{
  returnVal = boost::lexical_cast<T>(str.toStdString());
}

References:

Upvotes: 1

maxik
maxik

Reputation: 1123

Additionally you may use Qt's meta-object system, which works well with custom types.

struct MyStruct
{
    int i;
    ...
};
Q_DECLARE_METATYPE(MyStruct)

...

MyStruct s;
QVariant var;
var.setValue(s); // copy s into the variant

...

// retrieve the value
MyStruct s2 = var.value<MyStruct>();

Note that a QVariant can easily be converted into a QString.


Some more detailed reading is here.

Upvotes: 2

Jarod42
Jarod42

Reputation: 217065

You may use stream:

template<typename T>
void getValueFromString(QString str, T& returnVal)
{
    QTextStream stream(str);
    stream >> returnVal;
}

Upvotes: 3

Related Questions