该文档似乎对此不屑一顾,并且我在StackOverflow和其他地方看到了很多模棱两可的示例代码,所以...

如果我有一个实现AQAbstractProxyModel类和一个实现B的类QAbstractItemModel,并且我在A实例上调用了setSourceModel(b)方法,其中bB的实例,那么该方法会自动处理转发更新信号,例如modelResetrowsInserted等?还是我必须手动连接所有这些?

最佳答案

如果是class A : public QAbstractProxyModelclass 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;
}

...

08-04 01:55