将 QComboBox 与 QSqlQueryModel 一起使用
Using QComboBox with QSqlQueryModel
为了加快 QComboBox
处理非常大的数据集,想尝试使用 QSqlQueryModel
而不是 QStandardItemModel
。但是 QComboBox
中的文本数据我需要映射到一个 ID,该 ID 当前由 itemData(rowIndex, Qt::UserRole)
存储和访问。在 QSqlQueryModel
查询中将有 2 列:ID 和 Text;并且 QComboBox setModelColumn(1)
被定义,即 Text.
如果 combobox->itemData(rowIndex, Qt::UserRole)
必须包含 ID,如何正确子类化或重新定义 QSqlQueryModel
?谁实施了这样的事情或知道 link 消息来源?如果我这样定义 QVariant QSqlQueryModel::data(const QModelIndex & item, int role = Qt::DisplayRole)
:
QVariant MySqlModel::data(const QModelIndex &index, int role) const
{
if(role == Qt::UserRole && index.column() == 1)
return QSqlQueryModel::data(this->index(index.row(), 0), Qt::DisplayRole);
return QSqlQueryModel::data(index, role);
}
它会起作用吗,即在这种情况下 combobox->itemData(rowIndex, Qt::UserRole)
是否会包含 ID?或者需要调查 Qt 来源?
是的,根据 QComboBox 代码应该可以工作:
QVariant QComboBox::itemData(int index, int role) const
{
Q_D(const QComboBox);
QModelIndex mi = d->model->index(index, d->modelColumn, d->root);
return d->model->data(mi, role);
}
将实施。
为了加快 QComboBox
处理非常大的数据集,想尝试使用 QSqlQueryModel
而不是 QStandardItemModel
。但是 QComboBox
中的文本数据我需要映射到一个 ID,该 ID 当前由 itemData(rowIndex, Qt::UserRole)
存储和访问。在 QSqlQueryModel
查询中将有 2 列:ID 和 Text;并且 QComboBox setModelColumn(1)
被定义,即 Text.
如果 combobox->itemData(rowIndex, Qt::UserRole)
必须包含 ID,如何正确子类化或重新定义 QSqlQueryModel
?谁实施了这样的事情或知道 link 消息来源?如果我这样定义 QVariant QSqlQueryModel::data(const QModelIndex & item, int role = Qt::DisplayRole)
:
QVariant MySqlModel::data(const QModelIndex &index, int role) const
{
if(role == Qt::UserRole && index.column() == 1)
return QSqlQueryModel::data(this->index(index.row(), 0), Qt::DisplayRole);
return QSqlQueryModel::data(index, role);
}
它会起作用吗,即在这种情况下 combobox->itemData(rowIndex, Qt::UserRole)
是否会包含 ID?或者需要调查 Qt 来源?
是的,根据 QComboBox 代码应该可以工作:
QVariant QComboBox::itemData(int index, int role) const
{
Q_D(const QComboBox);
QModelIndex mi = d->model->index(index, d->modelColumn, d->root);
return d->model->data(mi, role);
}
将实施。