现象

  • 程序崩溃
  • 调试报错:ASSERT failure in QList<T>::at: "index out of range"

注意

Qt QList等容器类调用at()前务必条件判断.

方法

QList<QString> myList = ...;
int index = 2;

//方法1,推荐
if(index>=0 && index < myList.size()) {
	//安全的
} else {
	qDebug() << "错误,超出范围";
}

//方法2,判断是否为空
if(myList.isEmpty()) {
	qDebug() << "列表为空";
} else {
	//非空
}

更多推荐