Add a QObject to the Qt combo box

I have a custom class that I created, say, MyClass. Now, how to add a link to the MyClass link as the second parameter in the combo box below:

this-> ui-> comboBox-> addItem ("item-1",);

The goal is that when the element has been changed, even it has been started, I want to get this instance of the MyClass class and process it accordingly.

+1
source share
2 answers

First you need to use Q_DECLARE_METATYPE(MyClass*) so that this type can be used in QVariant . Then you can add an element as follows:

 this->ui->comboBox->addItem("item-1", QVariant::fromValue(myClass)); 

And return it:

 this->ui->combobox->itemData(x).value<MyClass*>(); 
+5
source

The syntax above the answer is a little flawed,

use Q_DECLARE_METATYPE (MyClass *) in the MyClass header file so that this type can be used in QVariant.

add the item as follows:

this-> ui-> comboBox-> addItem ("item-1", QVariant :: fromValue (myClass));

And return it: this-> ui-> combobox-> ItemData (x) .value ();

+1
source

Source: https://habr.com/ru/post/1494591/


All Articles