这是最新文档的链接:
http://doc.qt.io/qt-5/model-view-programming.html#using-drag-and-drop-with-item-views
我最近编写了一些代码,用于对单个表格中的单元格进行内部移动,但在研究它时,我发现了一些其他有用的链接。
http://qt-project.org/forums/viewthread/14197
我使用上面链接中的代码并将其翻译为使用QTableView而不是QTableWidget:
void MyTableView::dropEvent(QDropEvent *event)
{
// TODO: switch to using EyeTrackerModel::dropMimeData instead
QPoint old_coordinates = QPoint(-1,-1);
int dropAction = event->dropAction();
if(currentIndex().isValid()) //Check if user is not accessing empty cell
{
old_coordinates = QPoint( currentIndex().row(), currentIndex().column() );
}
QTableView::dropEvent(event);
qDebug() << "Detected drop event...";
event->acceptProposedAction();
if( this->indexAt(event->pos()).isValid() && old_coordinates != QPoint(-1, -1))
{
qDebug() << "Drop Event Accepted.";
qDebug() << "Source: " << old_coordinates.x() << old_coordinates.y()
<< "Destination: " << this->indexAt(event->pos()).row()
<< this->indexAt(event->pos()).column()
<< "Type: " << dropAction;
emit itemDropped( old_coordinates.x(), old_coordinates.y(),
this->indexAt(event->pos()).row(),
this->indexAt(event->pos()).column(),
dropAction);
}
// resize rows and columns right after a move!
this->doAdjustSize();
}
即使以下答案适用于 Python,但在检查我可能遗漏的内容时它仍然对我有所帮助。
QT: internal drag and drop of rows in QTableView, that changes order of rows in QTableModel
这是我最近项目中与拖放相关的一些代码 sn-ps。我认为您已经拥有其中的大部分,但为了完整起见,我将它们包括在下面。
QAbstractTableModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent)
Qt::ItemFlags QAbstractTableModel::flags(const QModelIndex &index) const
{
Q_UNUSED(index)
// if(index.isValid())
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
// else
// return Qt::ItemIsDropEnabled | Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
QAbstractTableView(QWidget *parent) :
QTableView(parent)
{
setAcceptDrops(true);
setDefaultDropAction(Qt::MoveAction);
}
希望对您有所帮助。