QVariant.canConvert()
-
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>(); }how can i do?
@neeme See http://doc.qt.io/qt-5/qvariant.html
"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."
Put "123" into your string and you will see that v.value<int>() will return 123 and not 0.
You should use convert() instead of value(). convert() will return false if the current data in the QVariant cannot be converted to the type you want to convert it to.