gpt4 book ai didi

c++ - std::string 和 QVariant 之间的转换(反之亦然)Qt5

转载 作者:行者123 更新时间:2023-11-30 05:12:02 32 4
gpt4 key购买 nike

我很难将 std::string 转换为 QVariant 并将 QVariant 转换回 std::string。在这两种情况下,我都得到空值(默认 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());
}

我发现了一个与此类似的问题,这就是它的工作原理。我还做了提到的答案的其他事情,所以在我的 main.cpp 中我有这个:

qRegisterMetaType<std::string>("std::string");

在我的 testitemlistmodel.h 中我有这个(在类声明之前):

Q_DECLARE_METATYPE(std::string)

我用的是Qt5.8。

编辑

我找到了此类转换的来源:http://www.qtcentre.org/threads/45922-best-way-to-extend-QVariant-to-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 有一个 constructor对于可以从 std::string 构建的 QStringQVariant 对象可以转换为 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::string 和 QVariant 之间的转换(反之亦然)Qt5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44750257/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com