Qt在QVariant抛出非法错误

Qt Throwing Illegal Error at QVariant

本文关键字:非法 错误 QVariant Qt      更新时间:2023-10-16

我有一些代码旨在从一组数据中获取QMaps的QList。然后它应该遍历该列表中的所有 QMaps。由于某种原因,在尝试此操作时,我收到一些有关用于存储数据的QVector的错误。这是我的代码:

#include <QCoreApplication>
#include <QMap>
#include <QVariant>
#include <QDebug>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QList<QMap<QString, QVariant>> maps;
    QMap<QString, QVariant> item1;
    item1.insert("Item 1", QVariant::fromValue(1));
    maps.append(item1);
    foreach (const QMap<QString, QVariant> & map, maps)
    {
        qDebug() << map;
    }
    return a.exec();
}

错误:

..ErrorTestmain.cpp(17): warning C4002: too many actual parameters for macro 'Q_FOREACH'
..ErrorTestmain.cpp(17): error C2275: 'QVariant': illegal use of this type as an expression
C:Qt5.8msvc2015_64includeQtCore/qsharedpointer_impl.h(94): note: see declaration of 'QVariant'
..ErrorTestmain.cpp(17): error C2955: 'std::remove_reference': use of class template requires template argument list
D:Microsoft Visual Studio 14.0VCINCLUDExtr1common(301): note: see declaration of 'std::remove_reference'
..ErrorTestmain.cpp(17): error C2065: 'map': undeclared identifier
..ErrorTestmain.cpp(17): error C2143: syntax error: missing ')' before '>'
..ErrorTestmain.cpp(17): error C2059: syntax error: '>'
..ErrorTestmain.cpp(17): error C2065: '_container_': undeclared identifier
..ErrorTestmain.cpp(17): error C2228: left of '.control' must have class/struct/union
..ErrorTestmain.cpp(17): note: type is 'unknown-type'
..ErrorTestmain.cpp(17): error C2228: left of '.i' must have class/struct/union
..ErrorTestmain.cpp(17): note: type is 'unknown-type'
..ErrorTestmain.cpp(17): error C2228: left of '.e' must have class/struct/union
..ErrorTestmain.cpp(17): note: type is 'unknown-type'
..ErrorTestmain.cpp(17): error C2059: syntax error: ')'
..ErrorTestmain.cpp(17): error C2143: syntax error: missing ';' before 'for'
..ErrorTestmain.cpp(17): error C2059: syntax error: '='
..ErrorTestmain.cpp(17): error C2143: syntax error: missing ';' before '}'
..ErrorTestmain.cpp(17): fatal error C1004: unexpected end-of-file found

谢谢,是的,tagData->toMappedList()返回正确的 QMaps/数据集。

我直言,问题是模板内部的,。可悲的是,foreach只不过是对Q_FOREACH的呼吁,这是一个宏。它需要用逗号分隔的参数。但是由于模板,您有 2 个逗号。不久前我遇到了这个问题,尽管Qt Creator至少为我提供了error: macro "Q_FOREACH" passed 3 arguments, but takes just 2而不是您遇到的大量错误。在您的情况下,这将是:

..ErrorTestmain.cpp(17): warning C4002: too many actual parameters for macro 'Q_FOREACH'

我建议使用迭代器进行for循环,以遍历映射列表。除非您想转储const在这种情况下,您可以执行以下操作:

QMap<QString, QVariant> map;
foreach (map, maps) {
    ...
}

您也可以使用auto但再次 - 没有恒定性。

如果常量是您的情况下的一个关键方面,请使用常量迭代器的for循环。