我很难将std :: string转换为qvariant,qvariant又回到std :: string。在这两种情况下
这些是我代码的相关部分:
bool TestItemListModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
// processing of other function arguments, checks, etc.
(*myData)[row].setName(value.value<std::string>());
// here I end up with ""
}
QVariant TestItemListModel::data(const QModelIndex &index, int role) const
{
// again all the checks, etc.
return QVariant::fromValue<std::string>((*myData)[row].getName());
}
我找到了一个与这个类似的问题,这就是它的工作原理。我还做了其他答案,所以在我的主角中。我有一个:
qRegisterMetaType<std::string>("std::string");
,在我的testItemlistModel.h中,我有这个(在班级声明之前(:
Q_DECLARE_METATYPE(std::string)
我使用QT5.8。
编辑
我找到了这种类型的转换的来源:http://www.qtcentre.org/threads/45922-best-way-way-way-to-extend-qvariant-to-support-to-support-support-std-string?p=208049#post208049。现在我只是意识到它已经很老了,可能不再起作用了。如果是这样,那么最好的方法是什么?
使用QString
作为中位类型怎么样?它有点开销,但维护代码容易得多:
/* std::string to QVariant */ {
std::string source { "Hello, World!" };
QVariant destination;
destination = QString::fromStdString(source);
qDebug() << destination;
}
/* QVariant to std::string */ {
QVariant source { "Hello, World!" };
std::string destination;
destination = source.toString().toStdString();
qDebug() << destination.c_str();
}
QVariant
具有QString
的构造函数,可以通过std::string
构建,并且可以将QVariant
对象转换为QString
,可以覆盖为std::string
。
另一个选项是使用QByteArray
而不是QString
,它仅复制您的 std::string
字符,而不会像QString
一样将其转换为Unicode:
// std::string to QVariant
myQVariant.setValue<QByteArray>(myStdString.c_str());
// std::string to QVariant
myStdString = myQVariant.value<QByteArray>().constData();