qtqlistqmap

How to store data in QMap & Qlist in QT?


How to store data in QMap & Qlist and retrieve them in QT ?

My requirement is I have Schedule Name which are Monday - Sunday and Schedule Items like "Sunday , 12:00 - 17:30".........

Now I want to have 2 QlistWidget one contains schedule names and other contains Schedule items , now when i select one Schedule name in first listbox corresponding related schedule item gets listed in another listbox.

How can I add items to listwidget using Qmap and Qlist?

How to keep data in memory using it?

  QList<QString> ScheduleItemslist;
     ScheduleItemslist << "Saturday,09:00- 17:30" << "Sunday,10:00- 12:00" << "Sunday,01:30- 17:30" ;

 QList<QString> ScheduleItemslst;
  ScheduleItemslst << "Monday,09:00- 17:30" << "Tuesday,10:00- 12:00" << "Wednesday,01:30- 17:30" ;


QMap<QString,QList<QString> > map;
map["Weekend Plus"] = ScheduleItemslist ;
map["All"] = ScheduleItemslst ;

foreach (QString key, map.keys())
{
    ui->listWidgetTimeSet->addItem (key) ;
}


ui->listWidgetTime->addItems(ScheduleItemslist);

In ItemselectionChanged Event :

QList<QString> ScheduleItemslist;
     ScheduleItemslist << "Saturday,09:00- 17:30" << "Sunday,10:00- 12:00" << "Sunday,01:30- 17:30" ;

  QList<QString> ScheduleItemslst;
    ScheduleItemslst << "Monday,09:00- 17:30" << "Tuesday,10:00- 12:00" << "Wednesday,01:30- 17:30" ;

if(ui->listWidgetTimeSet->currentItem()->text() == "Weekend Plus")
{
    ui->listWidgetTime->addItems(ScheduleItemslist);
}
else if (ui->listWidgetTimeSet->currentItem()->text() == "All")
{
    ui->listWidgetTime->addItems(ScheduleItemslst);
}

Solution

  • You need something like this to store your data.

    //Declare your map
    QMap <QString, QList <QString> > map;
    
    //Populate your map in a function
    void populateMap ()
    {
    
        QList<QString> sundaylist;
        sundaylist<< "Sunday , 12:00 - 17:30" << "Sunday , 18:00 - 20:30";
        map ["Sunday"] = sundaylist;
    
        QList<QString> mondaylist;
        mondaylist<< "Monday , 12:00 - 17:30" << "Monday , 18:00 - 20:30";
        map ["Monday"] = mondaylist        
    }
    
    //Populate list1 with keys in your map
    void populateList1 ()
    {
        list1.addItems (map.keys ());
    }
    
    //This is your slot connected to currentItemChanged  signal of list1
    void list1CurrentItemChanged ( QListWidgetItem * current, QListWidgetItem * previous ) 
    {
        list2.clear ();
        QString key = current->text ();
        list2.addItems (map [key]);
    
    }