【问题标题】:QCombobox doesn't select when changing currentIndex更改 currentIndex 时不选择 QCombobox
【发布时间】:2013-08-10 17:49:09
【问题描述】:

在我的构造函数中,我连接到一个 Sqlite 数据库并从中读取“类别”(QStrings)。 我将它们存储在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;
}

【问题讨论】:

  • 您应该指定您使用的 Qt 版本。
  • 没有选择,还是选择了错误的项目?
  • 当我启动应用程序时,没有选择任何内容,而是插入到 QCombobox。

标签: c++ qt qcombobox


【解决方案1】:

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

试着放 ui-&gt;cmbCategory-&gt;removeItem(0); 在 updateCategories 的开头检查是否是这种情况

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

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

【讨论】:

    猜你喜欢
    • 2012-11-15
    • 2013-01-13
    • 2016-05-08
    • 2019-11-05
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    相关资源
    最近更新 更多