开发者

Add QObject in the combo box of Qt

开发者 https://www.devze.com 2022-12-08 16:30 出处:网络
I have a custom class I created, say MyClass. Now how to add a reference to MyClass\'s reference as second parameter in the combo box below:

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

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

Purpose is to when item changed even is fired, i want 开发者_StackOverflowto get that specific class instance of MyClass and process accordingly.


First you need to use Q_DECLARE_METATYPE(MyClass*), so that the type can be used in QVariant. Then you can add the item like this:

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

And get it back:

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


Above answer syntax is slightly incorrect,

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

add the item like this:

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

And get it back: this->ui->combobox->itemData(x).value();

0

精彩评论

暂无评论...
验证码 换一张
取 消