-1

I have a function, which parses the file and fills a QMap<QString, int> with entries and returns a QVariant with value of that map:

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

When i check the contents of the map after calling it, i see an empty map:

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

This function works fine if i return QMap<QString, int>, but wrapping it in QVariant gives an empty map. Why might that be?

George
  • 578
  • 4
  • 21
  • 1
    You put `QMap` into the variant, but try to get `QMap` back. Either build `QMap` in `parseFile` and put that into the variant, or use `QVariant::value` to extract the correct type on the caller side. – Igor Tandetnik Jul 25 '21 at 20:54
  • @IgorTandetnik yep, you are right. `QVariant words = FileParser().parseFile(QCoreApplication::applicationDirPath() + "/Input.txt"); qDebug()<>();` gave me the desired result – George Jul 25 '21 at 21:02
  • @George please provide a [mre] – eyllanesc Jul 25 '21 at 21:14

1 Answers1

1

There is a mismatch where you put QMap<QString, int> into the variant, but tried to get QMap<QString, QVariant> back from the result. Either build QMap<QString, QVariant> in parseFile and put that into the variant, or use QVariant::value to extract the correct type on the caller side, i.e.:

qDebug() << words.value<QMap<QString, int>>();
Patrick Parker
  • 4,863
  • 4
  • 19
  • 51