更改currentIndex时,QCombobox不会选择

时间:2013-08-10 17:49:09

标签: c++ qt qcombobox

在我的构造函数中,我连接到Sqlite数据库并从中读取“Categories”(QString s)。 我将它们存储在QList中。我通过调试器检查了它们是否为空,但一切都很好。

我的初始值设定项列表中的int currCategoryIndex设置为0。由于QComboboxes从0开始索引,因此应该是第一项。

我的构造函数的摘录:

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

这是我读取数据库的部分,检查它是否为空,如果没有调用将这些类别添加到QComboBox的函数。

updateCategories()功能:

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
}

我的QCombobox中有所有项目但没有选中。我必须单击该框并自己选择一个。这不应该发生。

有什么问题?为什么不选择一个呢?

修改

currentIndexChanged信号:

void MainWindow::on_cmbCategory_currentIndexChanged(int index){
    currCategoryIndex = index;
}

1 个答案:

答案 0 :(得分:0)

也许第一项是空的? 由于您只向QComboBox添加项目,因此索引0(从头开始)可能是一个空字符串。

尝试推杆 ui->cmbCategory->removeItem(0); 在updateCategories的开头检查是否是这种情况

另外,如果currCategoryIndex是一个不存在的索引(例如-1),QComboBox也将为空(即使没有空字符串可供选择) - 在这种情况下,你可以尝试在函数中硬编码0(如果您希望项目始终是第一个),或添加其他检查,例如:

if (0 > currentCategoryIndex || currentCategoryIndex > ui->cmbCategory->count())
    currentCategoryIndex = 0