分享

Qt文件拖放操作

 ylsnData 2017-12-28

文件拖放技术是编程中的一项重要的技术,可以快速的打开文件,复制文件等

本文主要运用Qt中中的文件拖放事件实现图片的显示

1头文件
​#ifndef MYLABLE_H
#define MYLABLE_H

#include <QLabel>
#include <QDragEnterEvent>
#include <QMimeData>
#include <QString>
#include <QDebug>


class myLable : public QLabel
{
  //  Q_OBJECT
public:
    explicit myLable(QWidget *parent=0);
protected:
    void dragEnterEvent(QDragEnterEvent *event); //拖动事件进入
    void dropEvent(QDropEvent *);  //鼠标在本窗口放下
private:
    QString fileName;

};

#endif // MYLABLE_H

2源文件


#include "mylable.h"

myLable::myLable(QWidget *parent):
    QLabel(parent)
{
    fileName.clear();
    this->setAcceptDrops(true); //设置接收拖动事件
}

//鼠标拖动进入事件
void myLable::dragEnterEvent(QDragEnterEvent *event)
{
    QString path=event->mimeData()->text(); //得到路径
    if(fileName.isEmpty())
    {
        fileName=path;
    }
    else if(fileName!=path)
    {
        fileName=path;
    }
    event->accept();  //接收事件
}
//鼠标放下事件
void myLable::dropEvent(QDropEvent *)
{
    if(fileName.isEmpty())
        return;
    //将图片设置到标签中
    fileName.replace("file:///",""); //
    this->setPixmap(fileName);
    this->setScaledContents(true);
    qDebug()<<"fileName:"<<fileName;
}


源码文件:

拖放源码

总结:主要是用到Qt中的两个拖放事件,当将文件拖动到本窗口时,就会记录拖动的文件路径,当鼠标在本窗口放下时,就会打开所对应的文件路径。

博文索引  持续更新中。。。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多