拖动事件 dragEnterEvent、放置事件 dropEvent、resize事件resizeEvent的实现
拖动事件 dragEnterEvent
放置事件 dropEvent
resize事件resizeEvent
DragFileExample.h
#ifndef DRAGFILEEXAMPLE_H
#define DRAGFILEEXAMPLE_H#include <QWidget>
#include <QDragEnterEvent>
#include <QResizeEvent>
#include <QDropEvent>namespace Ui {
class DragFileExample;
}class DragFileExample : public QWidget
{Q_OBJECT
protected:void dragEnterEvent(QDragEnterEvent *event);void resizeEvent(QResizeEvent *event);void dropEvent(QDropEvent *event);public:explicit DragFileExample(QWidget *parent = nullptr);~DragFileExample();private:Ui::DragFileExample *ui;
};#endif // DRAGFILEEXAMPLE_H
DragFileExample.cpp
#include "dragfileexample.h"
#include "ui_dragfileexample.h"#include <QMimeData>
#include <QFileInfo>DragFileExample::DragFileExample(QWidget *parent): QWidget(parent), ui(new Ui::DragFileExample)
{ui->setupUi(this);ui->labPic->setScaledContents(true);//图片自适应大小this->setAcceptDrops(true);//窗体统一接受dropui->labPic->setAcceptDrops(false);//labPic不接受dropui->plainTextEdit->setAcceptDrops(false);//
}DragFileExample::~DragFileExample()
{delete ui;
}void DragFileExample::dragEnterEvent(QDragEnterEvent *event)
{ui->plainTextEdit->clear();ui->plainTextEdit->appendPlainText("dragEnterEvent事件开始");for(int i=0;i<event->mimeData()->urls().size();i++){//选中的拖动的文档的列表 通过event->mimeData() 来遍历QUrl url = event->mimeData()->urls().at(i);ui->plainTextEdit->appendPlainText(url.path());}if(event->mimeData()->hasUrls()){QString fileName = event->mimeData()->urls().at(0).fileName();QFileInfo fileinfo(fileName);QString ext = fileinfo.suffix().toUpper();if(ext=="JPG")event->acceptProposedAction();elseevent->ignore();}elseevent->ignore();
}void DragFileExample::resizeEvent(QResizeEvent *event)
{//窗口大小变化的时候,改变文本框的宽度,和图片框的宽度和高度QSize sz= ui->plainTextEdit->size();ui->plainTextEdit->resize(this->width()-10,sz.height());ui->labPic->resize(this->width()-10,this->height()-sz.height()-20);event->accept();
}void DragFileExample::dropEvent(QDropEvent *event)
{QString filename = event->mimeData()->urls().at(0).path();filename = filename.right(filename.length()-1);QPixmap pixmap(filename);ui->labPic->setPixmap(pixmap);event->accept();
}
总结
1. 按下鼠标mousePressEnter,然后拖动鼠标mouserMove到目标控件触发dragEnterEvent,最后放置触发dropEvent的过程
2.拖动的文件 通过event->mimeData()获取到文件的路径,然后通过QFileInfo获取文件的具体信息
QString fileName = event->mimeData()->urls().at(0).fileName();QFileInfo fileinfo(fileName);