Important: Please read the Qt Code of Conduct -

Compare QVariant in Qt6

  • In Qt5 is was possible to compare QVariants, but that functionality is now deprecated: Doc.
    But there is the function bool QMetaType::compare(const void *lhs, const void *rhs, int typeId, int *result) you can use. But the function always return false (no comparison possible). My code:

        QVariant left  = ...;
        QVariant right = ...;
        int res;
        if (!QMetaType::compare(,, left.type(), &res)) {
            qWarning() << "Can not compare " << left << " and " << right; // prints: Can not compare  QVariant(int, 0)  and  QVariant(int, 2)
            return 0;
        return res < 0;

    What am I doing wrong?

  • Lifetime Qt Champion


    Do you mean compare them for equality ?

  • No I want to know whether one is smaller than the other. The old code was simply:

    return left < right;

  • Lifetime Qt Champion

    See for a discussion on why it was deprecated.

  • @Christian-Ehrlicher I understand the reasons why they deprecate it. I have the same use-case as described there. So a solution seems to be:

    bool SortedModelVectorView::lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const{
        const auto left = ....;
        const auto right = ....;
        switch (left.type()) {
        case QVariant::Int: return left.value<int>() < right.value<int>();
        case QVariant::Bool: return left.value<bool>() < right.value<bool>();
        case QVariant::String: return left.value<QString>() < right.value<QString>();
        qWarning() << "Can not compare " << left << " and " << right << ". Type " << left.type() << " not handled";
        return 0;

    Where you have to implement all types that you will handle. Ok this is one solution, but still why says QMetaType::compare that a comparison is not possible?

  • @autoantwort

    You can Use

    return  QPartialOrdering::Less == QVariant::compare(left, right);

Log in to reply