For example, I have an Item class inherited from QObject .

How is it easier to convert QMap<QString, Item *> to QMap<QString, QObject *> ?

    2 answers 2

    You can simply pass from one to the other:

     QMap<QString, Item *> map1; map1["1"] = new Item(); map1["2"] = new Item(); map1["3"] = new Item(); QMap<QString, QObject *> map2; for (QString key : map1.keys()) { map2[key] = map1[key]; } qDebug() << map1; qDebug() << map2; 

    Console:

     QMap(("1", QObject(0x7997d98))("2", QObject(0x7997f28))("3", QObject(0x7997fc0))) QMap(("1", QObject(0x7997d98))("2", QObject(0x7997f28))("3", QObject(0x7997fc0))) 

      For std::map very simple:

        std::map<QString, Item *> items; // где-нибудь берем items item["one"] = new Item(...); item["two"] = new Item(...); // ... std::map<QString, Object *> objects(items.begin(), items.end()); 

      Qt is now not at hand and I can not check, but at 99% it will also work as it tends to be compatible with standard containers.

      And yet, none of my business is of course, but there is no point in using Qt containers. Qt itself in interfaces uses them very poorly, with the exception of QString and QVariant of course. These containers do not give any advantages, only an extra string for Qt.

      • one
        Alas, QMap does not have such a constructor. " These containers do not give any advantages ." Implicit sharing, java-style iterators, foreach? - yrHeTaTeJlb