[Interest] QVariant equality
Linos
info at linos.es
Thu Apr 4 09:43:08 CEST 2013
On 03/04/13 22:16, Thiago Macieira wrote:
> On quarta-feira, 3 de abril de 2013 21.21.39, Linos wrote:
>> Hello,
>> is this behavior intended?
>>
>> main.cpp
>> #include <iostream>
>> #include <QtCore/QVariant>
>>
>> int main(int argc, char *argv[])
>> {
>> QVariant null_valid(QVariant::Int);
>> QVariant not_null(0.0);
>> bool are_equal = (null_valid == not_null);
>>
>> std::cout << are_equal << std::endl;
>> std::cout << null_valid.type() << std::endl;
>> std::cout << not_null.type() << std::endl;
>> }
>>
>> prints this when executed:
>> 1
>> 2
>> 6
>>
>> So they are "equal", it seems a bit strange to me given one isNull, the
>> other have a value and the two variants don't even have the same types,
>> after change the value of not_null to 0.01 they are not equal.
>
> Yes, this behaviour is expected.
>
> Please avoid using QVariant's nullness (isNull) functionality. Its intended
> goal is to support SQL queries that differentiate between null and non-null.
> That is, it is a nullable type[1], but it works a little like a Maybe Type[2].
>
> However, if you do anything else with a null QVariant, it will behave as if it
> were non-null and had the default value for the type.
>
> In other words:
> QVariant n(QVariant::Int);
> n.isNull(); // == true
> n.toInt(); // == 0
> n.toDouble(); // == 0.0
>
> Finally, note that QVariant's equality operator compares *values*, not types.
> QVariant(0LL) == QVariant(0.0) == QVariant(0) == QVariant("0")
>
> [1] http://en.wikipedia.org/wiki/Nullable_type
> [2] http://en.wikipedia.org/wiki/Maybe_type
>
>
Thanks to both explanations, yes i detected this behavior when working with sql
models, checking if i should update the table or not but i have added the
correct check now that i know this.
Regards,
Miguel Angel.
More information about the Interest
mailing list