• 1766阅读
  • 2回复

QVariant.canConvert [复制链接]

上一主题 下一主题
离线neeme
 

只看楼主 倒序阅读 楼主  发表于: 2019-01-29
  

    int a = 100;
    QString str = "very good";
    QVariant v = str;
    if(v.canConvert<int>())
        a = v.value<int>();
  请问为什么 canConvert<int> 返回 true ?
  
开发平台:Ubuntu 16.04 64bit + Qt 5.9.4
运行平台:Ubuntu 16.04 64bit
离线neeme

只看该作者 1楼 发表于: 2019-01-29
    template <typename T>
    void read(QString capstr, QString key, T &val)
    {
        QVariant vt = m_settings->value(capstr + "/" + key, val);
        if(vt.canConvert<T>())
            val = vt.value<T>();
    }

具体应用是这样的
开发平台:Ubuntu 16.04 64bit + Qt 5.9.4
运行平台:Ubuntu 16.04 64bit
离线kaon

只看该作者 2楼 发表于: 2019-01-29
Using canConvert() and convert() Consecutively
When using canConvert() and convert() consecutively, it is possible for canConvert() to return true, but convert() to return false. This is typically because canConvert() only reports the general ability of QVariant to convert between types given suitable data; it is still possible to supply data which cannot actually be converted.

For example, canConvert(Int) would return true when called on a variant containing a string because, in principle, QVariant is able to convert strings of numbers to integers. However, if the string contains non-numeric characters, it cannot be converted to an integer, and any attempt to convert it will fail. Hence, it is important to have both functions return true for a successful conversion.
快速回复
限100 字节
 
上一个 下一个