0

In my constructor I connect to a Sqlite Database and read "Categories" (QStrings) from it. I store them in a QList. I checked via debugger if they're empty, but everything is fine.

The int currCategoryIndex is set to 0 in my initializer list. And since QComboboxes start indexing from 0 it should be the first item.

An extract from my constructor:

dm.readDB_C(c_list); //reads into c_list
if(c_list.count() > 0) //has 1 or more items
    updateCategories();

This is the part where I read the database, check if it's empty and if not call a function which adds those categories to a QComboBox.

updateCategories() function :

void MainWindow::updateCategories()
{
    for(int i = 0; i < c_list.count(); i++){

        if(ui->cmbCategory->findText(c_list[i]) != -1){ //-1 means "not found"
            continue;
        } else {
            ui->cmbCategory->addItem(c_list[i]); //Add to QCombobox
        }
    }
    ui->cmbCategory->setCurrentIndex(currCategoryIndex); //Should be the first item
}

I have all items in my QCombobox but none is selected. I have to click the box and select one myself. That's not supposed to happen.

What is wrong? Why doesn't it select one itself?

Edit:

currentIndexChanged signal:

void MainWindow::on_cmbCategory_currentIndexChanged(int index){
    currCategoryIndex = index;
}
Davlog
  • 2,162
  • 8
  • 36
  • 60

1 Answers1

0

Perhaps the first item is empty? Since you only add items to QComboBox, it is possible that index 0 is (from the beginning) an empty string.

try putting ui->cmbCategory->removeItem(0); in the beginning of updateCategories to check if it is the case

also, if currCategoryIndex is an index that does not exist (for example -1) QComboBox will also be empty (even if there is no empty string to choose) - in this case you can try to hardcode 0 in the function (if you want the item to always be the first one), or add additional check, for example:

if (0 > currentCategoryIndex || currentCategoryIndex > ui->cmbCategory->count())
    currentCategoryIndex = 0
Tomasz Lewowski
  • 1,935
  • 21
  • 29