QT本是就支持鼠标左键选中拖动的功能,Drag和Drop。查看以下示例:
拖动功能包含两个窗口:一个是源窗口,一个是目标窗口。
在源窗口需要实现:
void mousePressEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
在目标窗口需要实现:
//窗口进入拖动
void dragEnterEvent(QDragEnterEvent *event) override;
//拖动离开
void dragLeaveEvent(QDragLeaveEvent *event) override;
//拖动移动
void dragMoveEvent(QDragMoveEvent *event) override;
//拖动松开鼠标
void dropEvent(QDropEvent *event) override;
具体实现过程:
//记录拖拽初始位置
void DragListView::mousePressEvent(QMouseEvent *event) {
if (event->buttons() & Qt::LeftButton) {
startPos = event->pos();
_modelIndex = indexAt(event->pos());
}
}
void DragListView::mouseReleaseEvent(QMouseEvent *event) {
if ((event->pos() - startPos).manhattanLength() > 5) {
return;
}
QModelIndex index = indexAt(event->pos());
setCurrentIndex(index); //鼠标relesse时才选中
}
void DragListView::mouseMoveEvent(QMouseEvent *event) {
if (event->buttons() & Qt::LeftButton) {
if ((event->pos() - startPos).manhattanLength() < QApplication::startDragDistance()) {
return;
}
QModelIndex theDragIndex = indexAt(startPos);
theDragRow = theDragIndex.row();
setCurrentIndex(theDragIndex); //拖拽即选中
QStandardItemModel* slm = dynamic_cast<QStandardItemModel*>(model());
QStandardItem *curItem = slm->itemFromIndex(_modelIndex);
if (curItem == nullptr) {
return;
}
_selectJBCode = curItem->data().toInt();
//调用接口选中Item
_iDragItemJB->dragItem(_modelIndex);
//[1]把拖拽数据放在QMimeData容器中
QString text = curItem->text();
QIcon icon = curItem->icon();
QIcon icon_hover = curItem->icon();
QByteArray itemData;
QDataStream dataStream(&itemData, QIODevice::WriteOnly);
dataStream << _selectJBCode << text ;
QMimeData *mimeData = new QMimeData;
mimeData->setData(myMimeType(), itemData);
//[2]设置拖拽时的缩略图
Thumbnail *DragImage = new Thumbnail(this);
DragImage->setupThumbnail(icon_hover, text);
//DragImage->setIconSize(18); //default:20
QPixmap pixmap = DragImage->grab();
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->setPixmap(pixmap);
drag->setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2));
if (drag->exec(Qt::MoveAction) == Qt::MoveAction) {
}
}
}
目标窗口实现源码:
void Map2DCanvasEx::dragEnterEvent(QDragEnterEvent* event) {
if (event->mimeData()->hasFormat("DragListView/code-text")) {
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void Map2DCanvasEx::dropEvent(QDropEvent *event) {
//判断接收的是否是指定的对象
if (event->mimeData()->hasFormat("DragListView/code-text")) {
//获取拖拽时设置的数据
QByteArray itemData = event->mimeData()->data("DragListView/code-text");
QDataStream dataStream(&itemData, QIODevice::ReadOnly);
QString text;
int selectJBCode = -1;
dataStream >> selectJBCode >> text;
JBPlotManagerInst()->addJB(event->pos());
if (event->source() == this) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
aaa