2017-02-23 155 views
-1

在我的程序中我有一系列的选项卡,并赢得每个选项卡有一个组合框和QListWidget。我试图通过QListWidgetItem类型的指针读取QListWidget上的项目状态。程序在代码的这一点崩溃。我确定程序崩溃了,因为我用断点检查了它。QListWidgetItem指针导致程序崩溃

这是我的代码;

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。我该如何解决这个问题?我编码错了吗?

+0

“这可能是因为指针listItem指向无效位置或NULL。”大概?为什么不在发布之前在调试器中验证这一点?首先找出_exact_问题。 – MrEricSir

+0

你能解释一下如何在调试器上做到这一点吗?我是Qt编程的新手。学习我自己。任何意见将是有益的? – Vino

+0

您的代码不完整;特别是它似乎缺少'main()'函数和至少一个'#include'。请[编辑]你的代码,这是你的问题[mcve],然后我们可以尝试重现并解决它。你还应该阅读[问]。 –

回答

0

所以我修正了我的错误; 我做错的部分是我试图使用QComboBox::count()函数返回的值访问QListWidget上的项目。 组合框内的项目数为8;但是对于给定的QComboBox选择,此QListWidget上的数字项目为3.我通过添加另一个for循环来解决使用​​3210限制循环计数来循环遍历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; 
}