Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Cast QVariant to int



  • Hello,

    I have QVariant with int value on it:

    QVariant variant(3);
    

    Now I would like to do something like that:

    int value = variant;
    

    Of course I can't. I can't cast from QVariant to int. So I can use method toInt() from QVariant. But I would like to do that dynamically. I try:

    int value = ( variant.type() ) variant;
    

    Of course this doesn't work, but I would like something like that. Is there any way to do that?



  • @TomNow99
    But there isn't, for the same reason. QDataStream operator << needs to know the type at compile time, just the same question as before. Because we are C++ and that is a strongly typed language. Unless you're willing to stream it as a QVariant, which is not what you want.

    At the end of the day you can write a method just like you've shown just with the necessary ifs/switch for all the QVariant types you want to handle, which might be a dozen? Once you've written the method once, it's done.


  • Lifetime Qt Champion

    @TomNow99
    Hi
    Af far as i know - you cant really do that dynamic.

    Also if
    int value = ( variant.type() ) variant;
    did work, you would convert all to int which might not always be what you wanted.

    Can I ask what you need this for ?



  • @TomNow99 said in Cast QVariant to int:

    int value = ( variant.type() ) variant;

    It seems to me the whole point of C++ typing is that you simply cannot do anything like this.....



  • @JonB

    @mrjj Of course I know that

    int value = ( variant.type() ) variant;
    

    doesn't work and I know about "int" :)

    I have many QVariant variables and I would like to add them to QByteArray. But I can't add them to this Array like QVariant. I need to add them like int/char/double.

    So I would like do something like:

    QByteArray byte;
    QDataStream stream(&byte, QIODevice::WriteOnly);
    
    
    for( auto element: variants )
    {
        stream<<element; // here I have to cast QVariant to int/char/double
    }
    

    Of course I can do something like:

    if(metatype of element == metatype int )
    {
        stream<<element.toInt();
    }
    else if(metatype of element == metatype double )
    {
        stream<<element.toDouble();
    }
    

    But maybe is shorter solution?



  • @TomNow99
    But there isn't, for the same reason. QDataStream operator << needs to know the type at compile time, just the same question as before. Because we are C++ and that is a strongly typed language. Unless you're willing to stream it as a QVariant, which is not what you want.

    At the end of the day you can write a method just like you've shown just with the necessary ifs/switch for all the QVariant types you want to handle, which might be a dozen? Once you've written the method once, it's done.


Log in to reply