3Qt文件拖放操作

来源:互联网 发布:数据录入外包 编辑:程序博客网 时间:2024/06/09 05:13

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

本文主要运用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中的两个拖放事件,当将文件拖动到本窗口时,就会记录拖动的文件路径,当鼠标在本窗口放下时,就会打开所对应的文件路径。

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


原创粉丝点击