【QT】文件拖拽至窗体并打开文件(十)

一、逻辑思路

1、创建widget工程、添加新文件-class类,对类进行写入拖拽事件操作
2、类中dragEnterEvent函数为拖拽至窗体,此时鼠标不松开,但需要启用继续接收事件的标志,否则不能接收dropEvent事件
3、类中dropEvent函数为释放文件,此时鼠标松开
4、拖拽后展示的图片如下所示
【QT】文件拖拽至窗体并打开文件(十)_第1张图片

二、代码实现

widget.h

#ifndef WIDGET_H
#define WIDGET_H
#include "mylabel.h"
#include 

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private:
    Ui::Widget *ui;
    mylabel *lbl;
};

#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    lbl = new mylabel(this);
    lbl->setText("sssss");
    ui->gridLayout->addWidget(lbl,0,0,1,1);
}
Widget::~Widget()
{
    delete ui;
}

mylabel.h

#ifndef MYLABEL_H
#define MYLABEL_H

#include 
#include 
#include 
#include 

class mylabel : public QLabel
{
    Q_OBJECT
public:
    explicit mylabel(QWidget *parent = 0);
    void dragEnterEvent(QDragEnterEvent *event);
    void dropEvent(QDropEvent *event);
private:
    QString fileName;
};
#endif // MYLABEL_H

mylabel.cpp(主要代码)

#include "mylabel.h"
#include 


mylabel::mylabel(QWidget *parent) : QLabel(parent)
{
    fileName.clear();
    this->setAcceptDrops(true);//启用拖动事件
}
void mylabel::dragEnterEvent(QDragEnterEvent *event)
{
    QString path;
    path = event->mimeData()->text();
    if(fileName.isEmpty())
    {
        fileName = path;
    }
    else
    {
        if(fileName != path)
        fileName = path;
    }
    qDebug()<<"dragEnterEvent"<<fileName;
    event->accept(); //告诉程序继续王下面传递
}
void mylabel::dropEvent(QDropEvent *)
{
    if(fileName.isEmpty())
    {
        return;
        qDebug()<<"return"<<"dropEvent"<<fileName;
    }
    this->fileName.replace("file:///","");
    this->setPixmap(QPixmap(fileName));
    this->setScaledContents(true);
    qDebug()<<"dropEvent"<<fileName;
    this->fileName.clear();
}

你可能感兴趣的:(qt,qt)