qvariant as key in qhash

2019-07-07 08:01发布

问题:

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>.