[Interest] QVariant equality

Thiago Macieira thiago.macieira at intel.com
Wed Apr 3 22:16:46 CEST 2013


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
-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel Open Source Technology Center
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 190 bytes
Desc: This is a digitally signed message part.
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20130403/89a9a019/attachment.sig>


More information about the Interest mailing list