#pragma once#include#include #include #include #include class DragTabel : public QTableView{public: DragTabel(QWidget *parent = 0); void AddItem(QString aName);protected: void mousePressEvent(QMouseEvent *event); void mouseMoveEvent(QMouseEvent *event); void dragEnterEvent(QDragEnterEvent *event); void dragMoveEvent(QDragMoveEvent *event); void dropEvent(QDropEvent *event); void performDrag();private: QStandardItemModel *m_pModel; QPoint startPos;};
#include "DragTabel.h"DragTabel::DragTabel( QWidget *parent /*= 0*/ ): QTableView(parent){ m_pModel = new QStandardItemModel; m_pModel->setHorizontalHeaderItem(0,new QStandardItem(tr("name"))); setModel(m_pModel); setAcceptDrops(true);}void DragTabel::AddItem( QString aName ){ m_pModel->appendRow(new QStandardItem(aName));}void DragTabel::mousePressEvent( QMouseEvent *event ){ if (event->button() == Qt::LeftButton) startPos = event->pos(); QTableView::mousePressEvent(event);}void DragTabel::mouseMoveEvent( QMouseEvent *event ){ if (event->buttons() & Qt::LeftButton) { int distance = (event->pos() - startPos).manhattanLength(); if (distance >= QApplication::startDragDistance()) performDrag(); } QTableView::mouseMoveEvent(event); }void DragTabel::dragEnterEvent( QDragEnterEvent *event ){ DragTabel *source = (DragTabel *)((void*)(event->source())); if (source && source != this) { event->setDropAction(Qt::MoveAction); event->accept(); }}void DragTabel::dragMoveEvent( QDragMoveEvent *event ){ DragTabel *source = (DragTabel *)((void*)(event->source())); if (source && source != this) { event->setDropAction(Qt::MoveAction); event->accept(); }}void DragTabel::dropEvent( QDropEvent *event ){ DragTabel *source = (DragTabel *)((void*)(event->source())); if (source && source != this) { AddItem(event->mimeData()->text()); event->setDropAction(Qt::MoveAction); event->accept(); }}void DragTabel::performDrag(){ if (1) { QMimeData *mimeData = new QMimeData; mimeData->setText(m_pModel->data(currentIndex()).toString()); QDrag* drag = new QDrag(this); drag->setMimeData(mimeData); //drag->setPixmap(QPixmap(":/images/person.png")); if (drag->exec(Qt::MoveAction) == Qt::MoveAction) { } }}
然后就是支持自定义拖拽数据类型!