STD :: String和Qvariant(反之亦然)QT5之间的转换
conversion between std::string and QVariant (and vice versa) Qt5
我很难将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();
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 在cuda线程之间共享大量常量数据
- 在c代码之间共享数据的最佳方式
- Mix_Init和Mix_OpenAudio SDL之间的区别是什么
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 大小相等但成员数量不同的结构之间的性能差异
- 类与私有变量的其他类之间的线程安全性
- 如何在cpp文件之间切换窗口?在Qt中
- Qt5:使用QCommandLineParser类时出现奇怪的编译错误
- 线程之间的布尔停止信号
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 我想知道长双倍和双倍之间的区别
- STD :: String和Qvariant(反之亦然)QT5之间的转换
- 在两个Windows QT5之间进行通信
- 由于访问键和快捷键冲突,Qt4和Qt5之间的更改
- Qt5中的void QSqlQuery::clear()和void QSqlQuery::finish()之间有什么区别