这是我用于移动 QAbstractItemModel 中一行的 Qt::DisplayData 的简短实用程序:
void CopyRowData( QAbstractItemModel * pModelDst, const QAbstractItemModel * pModelSrc, int nRowDst, int nRowSrc, const QModelIndex &parentDst /*= QModelIndex()*/, const QModelIndex &parentSrc /*= QModelIndex()*/, int nRole /*= Qt::DisplayRole*/ )
{
if (parentSrc.isValid())
assert(parentSrc.model() == pModelSrc);
if (parentDst.isValid())
assert(parentDst.model() == pModelDst);
int nCols = pModelSrc->columnCount(parentSrc);
for (int i = 0; i < nCols ; ++i)
pModelDst->setData(pModelDst->index(nRowDst, i, parentDst), pModelSrc->index(nRowSrc, i, parentSrc).data(nRole), nRole);
}
bool MoveModelRows( QAbstractItemModel * pModel, int nSrcRow, int nDstRow, int nCount /*= 1*/, const QModelIndex &parent /*= QModelIndex()*/ )
{
if (nSrcRow < 0 || nSrcRow >= pModel->rowCount(parent) ||
nDstRow < 0 || nDstRow >= pModel->rowCount(parent))
return false;
if (nSrcRow == nDstRow)
return true;
int nDstRowNew = nSrcRow > nDstRow ? nDstRow : nDstRow + 1;
if (!pModel->insertRows(nDstRowNew, nCount, parent))
return false;
int nSrcRowNew = nSrcRow > nDstRow ? nSrcRow + nCount : nSrcRow;
for (int i = 0; i < nCount; ++i)
CopyRowData(pModel, pModel, nDstRowNew + i, nSrcRowNew + i, parent, parent);
pModel->removeRows(nSrcRowNew, nCount, parent);
return true;
}