QVariant::fromValue(QMap<QString, int>) returns 一张空地图

QVariant::fromValue(QMap<QString, int>) returns an empty map

我有一个函数,它解析文件并用条目填充 QMap 和 returns 具有该映射值的 QVariant:

QVariant FileParser::parseFile(QString filePath)
{
    QMap<QString, int> toReturn;
    ... (parse the file and fill the map)
    return QVariant::fromValue(toReturn);
}

调用地图后查看地图内容时,我看到一张空地图:

QMap<QString, QVariant> words = FileParser().parseFile(QCoreApplication::applicationDirPath() + "/Input.txt").toMap();
qDebug()<<words; //Gives QMap()

如果我 return QMap,这个函数工作正常,但是将它包装在 QVariant 中会得到一个空映射。为什么会这样?

您将 QMap<QString, int> 放入变体但试图从结果中取回 QMap<QString, QVariant> 的位置不匹配。在 parseFile 中构建 QMap<QString, QVariant> 并将其放入变量中,或者使用 QVariant::value 在调用方提取正确的类型,即:

qDebug() << words.value<QMap<QString, int>>();