QComboBox::setItemData doesn't update data as expected..



  • Here's the code:
    @
    class MyType
    {
    public:
    QString key;
    QString val;
    bool operator==(const MyType& other) const
    {
    return key == other.key;
    }

    bool operator<(const MyType& other) const
    {
        return key < other.key;
    }
    

    };

    Q_DECLARE_METATYPE(MyType)

    int main(int argc, char *argv[])
    {
    QApplication app(argc, argv);

    qRegisterMetaType<MyType>("MyType");
        QMetaType::registerComparators<MyType>();
    
    MyType mytype;
    mytype.key = "abc";
    mytype.val = "zxc";
    QComboBox* cmb = new QComboBox();
    cmb->addItem("123", QVariant::fromValue(mytype));
    
    qDebug() << "key:" << cmb->currentData().value<MyType>().key << " val:" << cmb->currentData().value<MyType>().val;
    //OutPut: key: "abc"  val: "zxc"
    
    mytype.val = "vbn";
    cmb->setItemData(cmb->currentIndex(), QVariant::fromValue(mytype));
    qDebug() << "key:" << cmb->currentData().value<MyType>().key << " val:" << cmb->currentData().value<MyType>().val;
    //OutPut: key: "abc"  val: "zxc"       Expected: key: "abc"  val: "vbn"
    
    return app.exec();
    

    }
    @

    Eventually I found out the trick by changing the implementation of the overridden comparator "==" into "{ return (key == other.key && val == other.val);}"
    But that's another way of diverging from my expectation. As the members of MyType are so named, when using QComboBox::findData, as long as MyType::key matches, that's the data I want.
    Is there any workaround about this?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.