QListWidgetItem指针导致程序崩溃

QListWidgetItem pointer causes program to crash

本文关键字:程序 崩溃 指针 QListWidgetItem      更新时间:2023-10-16

在我的程序中,我有一系列选项卡,并赢得了每个选项卡,有一个组合框和QListWidget。我正在尝试通过QListWidgetItem类型的指针读取QListWidget上项目的状态。该程序在代码的这一点上崩溃。我确定该程序在这里崩溃,因为我用断点对其进行了仔细检查。

这是我的代码;

void MainWindow::on_applyButton_clicked()
{
//Reset list
MainWindow::revenueList.clear();
QStringList itemList;
itemList <<"Revenue growth" << "Cost of revenue growth" << "Operating income growth"
        << "Net income growth" << "Total operating expense growth" << "Gross profit"
        << "Operating profit" << "Net profit";
//Processing income statement
//Loop through all itemsin ComboBox
int items = ui->inc_st_comb->count();
for(int currentItem = 0; currentItem < items; currentItem++)
{
    //Set to current index
    ui->inc_st_comb->setCurrentText(itemList.at(currentItem));
    //Point to QListWidget Item and read checkbox
    QListWidgetItem *listItem = ui->inc_st_list->item(currentItem);
    if(listItem->checkState() == Qt::Checked)
    {
        MainWindow::revenueList.append(true);
    }
    else if (listItem->checkState() == Qt::Unchecked)
    {
        MainWindow::revenueList.append(false);
    }
}
    qDebug() << "U: " << MainWindow::revenueList;
}

该程序在此块上崩溃;

if(listItem->checkState() == Qt::Checked)
 {
      MainWindow::revenueList.append(true);
 }
 else if (listItem->checkState() == Qt::Unchecked)
 {
      MainWindow::revenueList.append(false);
 }

这可能是因为指针listItem指向无效的位置或NULL。我该如何解决这个问题?我编码错误吗?

,所以我修复了错误;我做错了的一部分是,我试图使用QComboBox::count()函数返回的值访问QListWidget上的项目。组合盒中的物品数量为8;但是,对于给定的QComboBox选择,此QListWidget上的数字项为3。我通过使用QListWidget::count()限制循环计数来添加另一个循环以通过QListWidget上的项目循环解决。

这是我的工作代码;

void MainWindow::on_applyButton_clicked()
{
//Reset list
MainWindow::revenueList.clear();
QStringList itemList;
itemList <<"Revenue growth" << "Cost of revenue growth" << "Operating income growth"
        << "Net income growth" << "Total operating expense growth" << "Gross profit"
        << "Operating profit" << "Net profit";
//Processing income statement
//Loop through all itemsin ComboBox
int items = ui->inc_st_comb->count();
for(int currentItem = 0; currentItem < items; currentItem++)
{
    //Set to current index
    ui->inc_st_comb->setCurrentText(itemList.at(currentItem));
    for(int index = 0; index < ui->inc_st_list->count(); index++)
    {
         //Point to QListWidget Item and read checkbox
         QListWidgetItem *listItem = ui->inc_st_list->item(index);

         if(listItem->checkState() == Qt::Checked)
         {
             MainWindow::revenueList.append(true);
         }
         else if (listItem->checkState() == Qt::Unchecked)
         {
             MainWindow::revenueList.append(false);
         }
    }
}
   qDebug() << "U: " << MainWindow::revenueList;
}