How to show all keys inside QMap with QStringList?

naoufelabs picture naoufelabs · Sep 5, 2013 · Viewed 7k times · Source

I have a problem with QMap. Each key has many values. The idea is to show all values with its unique key. To iterate through this map with a QtGui application, I have the TextEdit (name: t2). The code is inside a button goes as:

void MainWindow::on_push2_clicked()
{
    QMap<int, QStringList> myMaps;
    myMaps[1].append("Autodesk Maya 2014");
    myMaps[1].append("Autodesk Inventor 2014");
    myMaps[1].append("Autodesk Alias 2014");
    myMaps[1].append("Autodesk 3ds Max 2014");
    myMaps[1].append("Autodesk Softimage 2014");
    myMaps[2].append("Adobe Photoshop CS6");
    myMaps[2].append("Adobe Illustrator CS6");
    myMaps[2].append("Adobe InDesign CS6");
    myMaps[1].append("Autodesk AutoCAD 2014");

    QStringList stsl; // the StringList which contains all values

    QMap<int, QStringList>::iterator it;

    for (it=myMaps.begin(); it!=myMaps.end(); ++it) {
    QString qsi=QString::number(it.key());
    QString qs=it.value().join(" - ");        
    stsl << "<span style='color:#FF1000;font-weight:bold;'>"+qsi + " : </span>"+ qs;
    }

      QString st4=stsl.join("<br/>"); //With setHtml
      ui->t2->setHtml(st4);
    }
}

// The output : 1 : Autodesk Maya 2014 - Autodesk Inventor 2014 - Autodesk Alias 2014 - Autodesk 3ds Max 2014 - Autodesk Softimage 2014 - Autodesk AutoCAD 2014 - Lightwave 12 2 : Adobe Photoshop CS6 - Adobe Illustrator CS6 - Adobe InDesign CS6.

// The output which I want to do: 1 : Autodesk Maya 2014 1 : Autodesk Inventor 2014 1 : Autodesk Alias 2014 1 : Autodesk 3ds Max 2014 1 : Autodesk Softimage 2014 1 : Autodesk AutoCAD 2014 2 : Adobe Photoshop CS6 2 : Adobe Illustrator CS6 2 : Adobe InDesign CS6

Answer

vahancho picture vahancho · Sep 5, 2013

I would rewrite it in the following way:

[..]
QMultiMap<int, QString> myMaps;

myMaps.insert(1, "Autodesk Maya 2014");
myMaps.insert(1, "Autodesk Inventor 2014");
myMaps.insert(1, "Autodesk Alias 2014");
myMaps.insert(1, "Autodesk 3ds Max 2014");
myMaps.insert(1, "Autodesk Softimage 2014");
myMaps.insert(2, "Adobe Photoshop CS6");
myMaps.insert(2, "Adobe Illustrator CS6");
myMaps.insert(2, "Adobe InDesign CS6");
myMaps.insert(1, "Autodesk AutoCAD 2014");

QMap<int, QString>::iterator it;
QString output;

for (it = myMaps.begin(); it != myMaps.end(); ++it) {
    // Format output here.
    output += QString("%1 : %2").arg(it.key()).arg(it.value());
}
[..]