Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update and sort Qt ComboBoxes alphabetically

I want to write a program, working like a little navigation system uisng the Qt framework, but i still am very new to it.

I created a dialog with two Comboboxes. Each combobox contains all "citynames". At the initialization the content of both boxes is sorted alphabetically.

If a name in the first box is selected, it should not be displayed in the second one and the other way too.

I successfully removed the item and added it again, if another item is selected, but know i cannot sort them anymore

This is what i tried so far for updating:

for(std::vector<City>::iterator iter = citylist.begin(); iter != citylist.end(); iter++){
    if(ui->combo2->currentText() != (*iter).getName()
            and ui->combo1->findText((*iter).getName()) == -1){
        ui->combo1->addItem((*iter).getName(),QComboBox::InsertAlphabetically);
    }
}

but it does not insert the items alphabetically...

so i tried to sort it afterwards:

 QSortFilterProxyModel* proxy = new QSortFilterProxyModel(ui->combo1);

proxy->setSourceModel(ui->combo1->model());

// combo's current model must be reparented,
// otherwise QComboBox::setModel() will delete it
ui->combo1->model()->setParent(proxy);

ui->combo1->setModel(proxy);

// sort
ui->combo1->model()->sort(0);

But if i try to call this function an error occurs and the application terminates.

So is anyone out there, who is able to help me?

like image 514
Justus Schock Avatar asked Jun 20 '15 17:06

Justus Schock


1 Answers

You were nearly there!

ui->comboBox1.addItem("myitem");
// qApp->processEvents();  not really needed
ui->comboBox1.model()->sort(0);
like image 125
guitarpicva Avatar answered Sep 28 '22 08:09

guitarpicva