- #ifndef PROJECTLISTWIDGET_H
- #define PROJECTLISTWIDGET_H
- #include <QtGui>
- class ProjectListWidget : public QListWidget
- {
- Q_OBJECT
- public :
- ProjectListWidget(QWidget *parent = 0);
- protected :
- void mousePressEvent(QMouseEvent *event);
- void mouseMoveEvent(QMouseEvent *event);
- void dragEnterEvent(QDragEnterEvent *event);
- void dragMoveEvent(QDragMoveEvent *event);
- void dropEvent(QDropEvent *event);
- private :
- void performDrag();
- QPoint startPos;
- };
- #endif // PROJECTLISTWIDGET_H
- #include "projectlistwidget.h"
- ProjectListWidget::ProjectListWidget(QWidget *parent)
- : QListWidget(parent)
- {
- setAcceptDrops( true );
- }
- void ProjectListWidget::mousePressEvent(QMouseEvent *event)
- {
- if (event->button() == Qt::LeftButton)
- startPos = event->pos();
- QListWidget::mousePressEvent(event);
- }
- void ProjectListWidget::mouseMoveEvent(QMouseEvent *event)
- {
- if (event->buttons() & Qt::LeftButton) {
- int distance = (event->pos() - startPos).manhattanLength();
- if (distance >= QApplication::startDragDistance())
- performDrag();
- }
- QListWidget::mouseMoveEvent(event);
- }
- void ProjectListWidget::performDrag()
- {
- QListWidgetItem *item = currentItem();
- if (item) {
- QMimeData *mimeData = new QMimeData;
- mimeData->setText(item->text());
- QDrag *drag = new QDrag( this );
- drag->setMimeData(mimeData);
- drag->setPixmap(QPixmap( ":/images/person.png" ));
- if (drag->exec(Qt::MoveAction) == Qt::MoveAction)
- delete item;
- }
- }
- void ProjectListWidget::dragEnterEvent(QDragEnterEvent *event)
- {
- ProjectListWidget *source =
- qobject_cast<ProjectListWidget *>(event->source());
- if (source && source != this ) {
- event->setDropAction(Qt::MoveAction);
- event->accept();
- }
- }
- void ProjectListWidget::dragMoveEvent(QDragMoveEvent *event)
- {
- ProjectListWidget *source =
- qobject_cast<ProjectListWidget *>(event->source());
- if (source && source != this ) {
- event->setDropAction(Qt::MoveAction);
- event->accept();
- }
- }
- void ProjectListWidget::dropEvent(QDropEvent *event)
- {
- ProjectListWidget *source =
- qobject_cast<ProjectListWidget *>(event->source());
- if (source && source != this ) {
- addItem(event->mimeData()->text());
- event->setDropAction(Qt::MoveAction);
- event->accept();
- }
- }
- void ProjectListWidget::mouseMoveEvent(QMouseEvent *event)
- {
- if (event->buttons() & Qt::LeftButton) {
- int distance = (event->pos() - startPos).manhattanLength();
- if (distance >= QApplication::startDragDistance())
- performDrag();
- }
- QListWidget::mouseMoveEvent(event);
- }
本 文出自 “豆子空间 ” 博客,请务必保留此出处http://devbean.blog.51cto.com/448512/286796