接受拖放
繼承QAbstractItemModel(根據(jù)自己實際情況可繼承其他Model)后腰根,重寫以下函數(shù)(注:需要在view(QTableView等)中開啟接受拖放setAcceptDrops(true))
Qt::ItemFlags MyModel::flags(const QModelIndex& index) const
{
auto defaultFlags = QAbstractTableModel::flags(index);
return defaultFlags | Qt::ItemIsDropEnabled; //開啟接受拖放
}
QStringList MyModel::mimeTypes() const
{
return QStringList() << "type1" << "type2"; //支持的拖放數(shù)據(jù)(MIME)類型
}
//判斷是否支持拖放的數(shù)據(jù)類型
bool MyModel::canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) const
{
if (!parent.isValid())
return false;
QStringList mimeFmts = data->formats();
for (const QString& fmt : mimeFmts)
{
if (fmt.contains("type1") || fmt.contains("type2"))
{
return true;
}
}
return QAbstractItemModel::canDropMimeData(data, action, row, column, parent);
}
//返回支持的數(shù)據(jù)操作
Qt::DropActions MyModel::supportedDropActions() const
{
return Qt::CopyAction | Qt::MoveAction;
}
//處理拖放的數(shù)據(jù)
bool MyModel::dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent)
{
QStringList mimeFmts = data->formats();
for (const QString& fmt : mimeFmts)
{
if (fmt.contains("type1"))
{
//添加處理
}
else if (fmt.contains("type2"))
{
//添加處理
}
}
return QAbstractItemModel::dropMimeData(data, action, row, column, parent);
}
支持拖拽
繼承QAbstractItemModel(根據(jù)自己時間情況可繼承其他Model)后,重寫以下函數(shù)(注:需要在view(QTableView等)中開啟接受拖放setDragEnabled(true))
Qt::ItemFlags MyModel::flags(const QModelIndex& index) const
{
auto defaultFlags = QAbstractTableModel::flags(index);
return defaultFlags | Qt::ItemIsDragEnabled; //開啟拖拽
}
繼承QStyledItemDelegate(根據(jù)自己時間情況可繼承其他Model)后颖杏,重寫以下函數(shù)
bool MyDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
static QPoint _dragStartPos;
if (event->type() == QEvent::MouseButtonPress)
{
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->buttons() & Qt::LeftButton)
{
_dragStartPos = mouseEvent->pos();
}
}
else if (event->type() == QEvent::MouseMove)
{
QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->buttons() & Qt::LeftButton)
{
if ((mouseEvent->pos() - _dragStartPos).manhattanLength() > QApplication::startDragDistance())
{
QDrag* drag = new QDrag((QObject*)option.widget);
QMimeData* mimeData = new QMimeData;
QByteArray bytes;
QDataStream out(&bytes, QIODevice::WriteOnly);
out << "dragData"; //填充拖拽數(shù)據(jù)
mimeData->setData(QString("type1"), bytes);
drag->setMimeData(mimeData);
drag->setPixmap(_dragPix);
drag->exec(Qt::MoveAction);
mimeData->deleteLater();
drag->deleteLater();
return true;
}
}
}
return QStyledItemDelegate::editorEvent(event, model, option, index);
}