使用QCombobox調用clear()來清除下拉框選項時,會出現程序崩潰的現象,而經過調試發現,問題出在
connect (ui->comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(slotNameCom(int)))中的槽函數,槽函數slotNameCom如下所示:
void C_Del_user::slotNameCom(int index)
{
Name_select = vecindex[index].name;
}
調試時發現,當程序執行ui->comboBox->clear ()時,會觸發currentIndexChanged(int)信號,槽函數slotNameCom()就會執行,且執行時槽函數中參數index爲-1,顯而易見,vecindex[-1]會導出程序崩潰(越界)。此時在槽函數中加入限制條件即可:
void C_Del_user::slotNameCom(int index)
{
if(index >= 0 && index < vecindex.size())
{
Name_select = vecindex[index].name;
}
}
也可以使用其他方法,在調用clear()前,先執行disconnect,此時就不會觸發信號,在clear()之後再connect。
如下:
disconnect(ui->comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(slotNameCom(int)));
ui->comboBox->clear();
connect(ui->comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(slotNameCom(int)))
最近發現了屏蔽函數,也可以適用:
ui->comboBox->blockSignals(true);//true屏蔽信號
ui->comboBox->clear();
ui->comboBox->blockSignals(false);
結尾
只爲記錄,只爲分享! 願所寫能對你有所幫助。不忘記點個贊,謝謝~