该文档似乎对此不屑一顾,并且我在StackOverflow和其他地方看到了很多模棱两可的示例代码,所以...
如果我有一个实现A
的QAbstractProxyModel
类和一个实现B
的类QAbstractItemModel
,并且我在A
实例上调用了setSourceModel(b)
方法,其中b
是B
的实例,那么该方法会自动处理转发更新信号,例如modelReset
, rowsInserted
等?还是我必须手动连接所有这些?
最佳答案
如果是class A : public QAbstractProxyModel
,class B : public QAbstractItemModel
,则某些信号正在转发和更新良好(dataChanged
等)。但是有些(例如rowsInserted
)您必须手动更正。
我使用这样的代码:
...
#define COL_ID 0
void A::setSourceModel(QAbstractItemModel *newSourceModel) {
beginResetModel();
if (this->sourceModel()) { // disconnect sourceModel signals
...
}
...
QAbstractProxyModel::setSourceModel(newSourceModel);
if (this->sourceModel()) { // connect sourceModel signals
...
connect(this->sourceModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(sourceRowsInserted(QModelIndex, int, int)));
...
}
return;
}
...
void A::sourceRowsInserted(const QModelIndex &parent, int first, int last) {
QModelIndex parentIndex = this->mapFromSource(parent);
QModelIndex sourceTopIndex = this->sourceModel()->index(first, COL_ID, parent);
QModelIndex sourceBottomIndex = this->sourceModel()->index(last, COL_ID, parent);
QModelIndex topIndex = this->mapFromSource(sourceTopIndex);
QModelIndex bottomIndex = this->mapFromSource(sourceBottomIndex);
beginInsertRows(parentIndex, topIndex.row(), bottomIndex.row());
endInsertRows();
return;
}
...