自定义QAbstractItemModel作为QComboBox模型出现Undefined赋值错误如何解决
问题原因
- 核心问题1:
index方法实现错误
你当前直接返回空QModelIndex,视图无法获取合法索引定位数据,即便rowCount返回正确值,也无法读取对应行内容。如果是一维列表场景,更推荐继承QAbstractListModel,框架会默认实现index、parent、columnCount等基础方法,避免手写错误。 - 核心问题2:
data方法未做角色判断,且未适配ComboBox的默认角色
你直接忽略了role参数,且Qt Quick Controls 2的ComboBox默认读取Qt::DisplayRole角色的值作为currentText,你当前自定义的textRole没有和默认角色兼容,导致ComboBox拿不到展示文本,出现undefined赋值错误。
修改方案
第一步 修改LcuModel.cpp的index方法
QModelIndex LcuModel::index(int row, int column, const QModelIndex &parent) const { // 列表模型父项无效、列数不为0、行越界时返回空索引 if (parent.isValid() || column != 0 || row < 0 || row >= iniFiles_.size()) return QModelIndex(); return createIndex(row, column); }
第二步 修改LcuModel.cpp的data方法,增加角色判断
QVariant LcuModel::data(const QModelIndex & index, int role) const { int row = index.row(); if (!index.isValid() || row < 0 || row >= iniFiles_.count()) { return QVariant(); } // 同时兼容自定义的textRole和ComboBox默认的Qt::DisplayRole if (role == textRole || role == Qt::DisplayRole) { return iniFiles_.at(row); } return QVariant(); }
可选优化:直接继承QAbstractListModel
如果你的场景就是一维列表,直接将基类从QAbstractItemModel改为QAbstractListModel,可以删掉你手写的parent、columnCount、index方法,框架会默认实现正确逻辑,代码更简洁。
修改后重新编译运行,报错就会消失,ComboBox的currentText也能正常拿到选中的文件名。
内容的提问来源于stack exchange,提问作者Soňa
相关产品推荐
相关产品推荐

