qvariant as key in qhash

送分小仙女□ 提交于 2019-12-10 20:24:14

问题


I want to create a data structure with QVariants a keys. It looks like this:

QHash<QPair<QVariant, QVariant>, SHAPES::Shape* > _shapes;

Unfortunately there is "no matching function for call to ‘qHash(const QVariant&)’".

So I defined my own implementation of qHash for QVariants:

#pragma once

#include <QVariant>
#include <QHash>

uint qHash( const QVariant & var )
{
    if ( !var.isValid() || var.isNull() )
        //return -1;
        Q_ASSERT(0);

    switch ( var.type() )
    {
        case QVariant::Int:
                return qHash( var.toInt() );
            break;
        case QVariant::UInt:
                return qHash( var.toUInt() );
            break;
        case QVariant::Bool:
                return qHash( var.toUInt() );
            break;
        case QVariant::Double:
                return qHash( var.toUInt() );
            break;
        case QVariant::LongLong:
                return qHash( var.toLongLong() );
            break;
        case QVariant::ULongLong:
                return qHash( var.toULongLong() );
            break;
        case QVariant::String:
                return qHash( var.toString() );
            break;
        case QVariant::Char:
                return qHash( var.toChar() );
            break;
        case QVariant::StringList:
                return qHash( var.toString() );
            break;
        case QVariant::ByteArray:
                return qHash( var.toByteArray() );
            break;
        case QVariant::Date:
        case QVariant::Time:
        case QVariant::DateTime:
        case QVariant::Url:
        case QVariant::Locale:
        case QVariant::RegExp:
                return qHash( var.toString() );
            break;
        case QVariant::Map:
        case QVariant::List:
        case QVariant::BitArray:
        case QVariant::Size:
        case QVariant::SizeF:
        case QVariant::Rect:
        case QVariant::LineF:
        case QVariant::Line:
        case QVariant::RectF:
        case QVariant::Point:
        case QVariant::PointF:
            // not supported yet
            break;
        case QVariant::UserType:
        case QVariant::Invalid:
        default:
            return -1;
    }

    // could not generate a hash for the given variant
    return -1;
}

But then the compiler says, that the method is defined multiple times.

So, how to use QVariant as keys in QHash? Or: what am I doing wrong?


回答1:


It seems that your qHash implementation is placed in a header file. You need to declare it in header file without implementation:

uint qHash( const QVariant & var );

Implementation should be placed in the respective source file.

Also note that qHash() declaration should be placed before #include <QHash>.



来源:https://stackoverflow.com/questions/17208813/qvariant-as-key-in-qhash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!