Important: Please read the Qt Code of Conduct -

How can i get an unsorted qmap?

  • Is it possible to set up a QMap that returns the keys in the order in which they were added?
    I have created my whole program using a qmap and i would prefer not to change the qmap with sth else.

  • No. QMap is sorted by the key. You could use a QHash + a QList or something like that.

  • I suggest you read "this": so you get an understanding of what sort of container classes exist and what their individual characteristics are.

    If you want "first in first out" including a Key -> Value entry I'd suggest you use a QQueue holding QPairs


    This way you will loose the benefit of QMap which is quick acccess to elements via their key, but you gain the advantage of quicker insertion and deletion of elements.

  • Hi,

    I changed my code and I created a qlist with qmap, but I cant find a way to check the key of my qmap. I have a qlist qmap with some data e.g.(id,1),(test_id, “a”) and I use the code that follows to write some data to a file. But I would like to write different data if the key of the map is “id” and different if it is “test_id”. How can I check the key?

    @ QMultiMap<QString, QString>::iterator lab_id = examinations.find("lab_id");
    QMultiMap<QString, QString>::iterator test_id = examinations.find("test_id");

         while(!chosen_examinations2.isEmpty()) {
              QMap<QString,QString> exam = chosen_examinations2.takeFirst();
            if (exam.key()=="id"){ //**here how can i check this?? , i get an error
            xmlWriter->writeCharacters (exam["id"]);
            while (exam["test_id"]!=test_id.value())
               { test_id++;
            xmlWriter->writeCharacters (test_id.value());

  • I do not think that your approach is a good idea.

    You use a map and you are not satisfied, because of sorting through the map. Wrapping the QMap with QList just puts the whole as is into another container, but it will not change the situation regarding the sorting. It gets only complicated.

    You need to substitute QMap with QList. Unfortunately, you have to carry all the pain in changing your source. There is no easy escape route.

  • Again having a QList of QMaps doesn't make sense for your use case.

    One way to solve your problem without you having to remove your old QMap stuff might be to store a QQueue additionally. The QQueue just holds the keys for the QMap values in the order in which they were inserted. This way you store the order in which the values were entered into the map in the QQueue and can access the values inside the QMap using this keys from the QQueue.

    BUT for this to work you need to change the keys you use for your QMap to something unique (i.e. NOT "id" or "test_id"). The id and test_id stuff could be stored as a sort of property parameter of the value you store in the map.

  • thanks. solved

Log in to reply