将QStrings转换为其他类型

时间:2016-06-28 08:09:02

标签: c++ qt qstring

我想将QStrings转换为不同的类型。我想尽可能地做到这一点,而不必为每种类型编写明确的方法。

我想过使用模板函数,如下所示:

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

显然这不起作用,但我希望有类似的东西。

有一种简单的方法吗?

4 个答案:

答案 0 :(得分:3)

QString有很多转换方法,您可能不需要新功能,例如:

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

我不确定是否可以从QString继承,但你可以从中创建一个子项并覆盖强制转换。您可以覆盖类的强制转换,例如:

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

int x = static_cast<int>(aCircle);

同样,覆盖static_cast的{​​{1}}并不合乎逻辑。

答案 1 :(得分:3)

您可以使用流:

 border-top: 2px solid #00b9ff;
    height: 340px;
    overflow: hidden;

答案 2 :(得分:2)

此外,您可以使用Qt's meta-object system,它适用于自定义类型。

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>();

请注意,QVariant可以轻松转换为QString

更详细的阅读是here

答案 3 :(得分:1)

如果Boost是一个选项,你可以写:

#include <boost/lexical_cast.hpp>

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

参考文献: