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

How to extract a custom object from QVariant?



  • I'm using low level pcap library, to get interfaces, and put them inside combo box, with the associated name, so user can select, which to use. I use qvariant constructor QVariant(int typeId, const void * copy)

     pcap_if * devs = GetDevices();
     for(auto d = devs; d != nullptr; d = d->next){
            this->ui->comboInterfaces->addItem(d->description, QVariant(0,d));
        }
    

    But how can i extract the pcap_if * pointer to object from qvariant?

    I try like that:

    Q_DECLARE_METATYPE(pcap_if *);
    pcap_if * test = data.value<pcap_if*>();
    

    test is null. How can i extract my pointer? Help



  • Hello,

    You can try to put Q_DECLARE_METATYPE(pcap_if *); after the class declaration.

    class pcap_if 
    {
    public:
        pcap_if ()
        {
        }
    };    
    Q_DECLARE_METATYPE(pcap_if *)
    

    And you have to use QVariant::setValue() or QVariant::fromValue() to set the pointer value correctly:

      pcap_if * devs = GetDevices();
      for(auto d = devs; d != nullptr; d = d->next){
        this->ui->comboInterfaces->addItem(d->description, QVariant::fromValue(d));
        //or 
        //QVariant v;
        //v.setValue(d);
        //this->ui->comboInterfaces->addItem(d->description, v);
      }
    

    edit: Another point, I didn't find any QVariant's constructor with two arguments, what did you try to achieve with QVariant(0, d) ? I did find it finally :)

    See this post: https://stackoverflow.com/questions/44501171/qvariant-with-custom-class-pointer-does-not-return-same-address



  • But pcap_if _t* is not my class it is a low level struct defined inside pcap library from pcap.h:

    /*
     * Item in a list of interfaces.
     */
    struct pcap_if {
    	struct pcap_if *next;
    	char *name;		/* name to hand to "pcap_open_live()" */
    	char *description;	/* textual description of interface, or NULL */
    	struct pcap_addr *addresses;
    	bpf_u_int32 flags;	/* PCAP_IF_ interface flags */
    };
    

    . But from what you respond iguess i can wrap it inside some class.



  • @BeefTaco Ok, I think you can put it in the main, or at some place in your code where it is executed before you use it with a QVariant.



  • As an alternative, you could also cast it to a void *, as suggested by the second reply on the stackoverflow's post I referred.


Log in to reply