ComboBox and QAbstractListModel
-
How can I use QAbstractListModel as a model for ComboBox? It works fine with ListView, but when I set it as a model for ComboBox, my application generates the following warning at startup:
ComboBox.qml:510: ReferenceError: modelData is not defined"textRole" also does not work
-
Hi,
Can you post the relevant code ? It is tougher to guess the problem without it.
-
ComboBox { model: ShipsModel textRole: name }
Model:
ShipsModel::ShipsModel(QObject *parent) : QAbstractListModel(parent) { } int ShipsModel::rowCount(const QModelIndex & parent) const { Q_UNUSED(parent); return m_data.count(); } QVariant ShipsModel::data(const QModelIndex & index, int role) const { if (index.row() < 0 || index.row() >= m_data.count()) return QVariant(); const ShipsItem &item = m_data[index.row()]; if (role == NameRole) return item.name(); else if (role == SizeRole) return item.size(); return QVariant(); } bool ShipsModel::setData(const QModelIndex &index, const QVariant &value, int role) { ShipsItem *item = &m_data[index.row()]; if (index.isValid() && role == Qt::EditRole) { if(index.column()==0){ item->setName(value.toString()); emit dataChanged(index, index); } if(index.column()==1){ item->setSize(value.toInt()); emit dataChanged(index, index); } return true; } return false; } QHash<int, QByteArray> ShipsModel::roleNames() const { QHash<int, QByteArray> roles; roles[NameRole] = "name"; roles[SizeRole] = "size"; return roles; }
This code works well:
ListView { model: ShipsModel delegate: TextField { text: name } }
-
textRole expects a string so it should be "name"
ReferenceError: modelData is not defined would occur when the Combobox is created (and thus model is set) before the model is actually initialized.