2017-02-23 306 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; 
}