接受拖放
继承QAbstractItemModel(根据自己时间情况可继承其他Model)后,重写以下函数(注:需要在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"; //支持的拖放数据(MIME)类型
}
//判断是否支持拖放的数据类型
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);
}
//返回支持的数据操作
Qt::DropActions MyModel::supportedDropActions() const
{
return Qt::CopyAction | Qt::MoveAction;
}
//处理拖放的数据
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(根据自己时间情况可继承其他Model)后,重写以下函数(注:需要在view(QTableView等)中开启接受拖放setDragEnabled(true))
Qt::ItemFlags MyModel::flags(const QModelIndex& index) const
{
auto defaultFlags = QAbstractTableModel::flags(index);
return defaultFlags | Qt::ItemIsDragEnabled; //开启拖拽
}
继承QStyledItemDelegate(根据自己时间情况可继承其他Model)后,重写以下函数
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"; //填充拖拽数据
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);
}
网友评论