QT打开文本文件(拖拽打开和QFileDialog两种方式)

一、前言

分别使用拖拽打开和QFileDialog两种方式实现了打开文本文件并显示,效果图如下:

 

二、实现步骤

1、实现ui界面,并将AcceptDrop应设置为True,plainTextEdit的属性设置为false

plainTextEdit的AcceptDrop属性默认是True,当我们拖动文件到plainTextEdit的时候,默认会响应拖动事件,并将文件路径显示出来。

主界面的AcceptDrop属性默认是false。

 

2、重写主界面的dragEnterEvent和dropEvent方法

  • dragEnterEvent

This event handler is called when a drag is in progress and the mouse enters this widget. The event is passed in the event parameter.

//当用户拖动文件到主窗口时候,就会触发dragEnterEvent事件
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    //判断拖拽文件类型,文件名 接收该动作
    if (event->mimeData()->hasFormat("text/uri-list"))
    {
        event->acceptProposedAction();
    }
}

 

  • dropEvent

This event handler is called when the drag is dropped on this widget. The event is passed in the event parameter.

//当用户放下这个文件后,就会触发dropEvent事件
void MainWindow::dropEvent(QDropEvent *e)
{
    if (!e->mimeData()->hasUrls())
    {
        return;
    }
    //e->mimeData()->urls()[0].toLocalFile()就可以得到拖动文件的文件路径了
    emit userDropFile(e->mimeData()->urls()[0].toLocalFile());//发送userDropFile信号
}

 

3、根据文件获取到的文件名打开文件,读取文件,并显示到plainTextEdit

 

三、源代码

  • mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;

public:
    void doOpenFile(const QString &path);

protected:
    void dropEvent(QDropEvent *e) override;//重写QDropEvent方法
    void dragEnterEvent(QDragEnterEvent *event) override;//重写dragEnterEvent方法

signals:
    void userDropFile(const QString& path);//拖动文件信号

};
#endif // MAINWINDOW_H
  • mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>

#include <QTextCodec>
#include <QTextStream>
#include <QMimeData>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //绑定信号和槽函数   支持拖动方式打开文件
    connect(this, &MainWindow::userDropFile, [this](const QString& path){
        doOpenFile(path);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_pushButton_clicked()
{
    QString fileFull;
    fileFull = QFileDialog::getOpenFileName(this,tr("打开文件"),"",tr("text(*)"));  //获取整个文件名
    if (fileFull.isEmpty())
    {
        return;
    }
    doOpenFile(fileFull);
}

void MainWindow::doOpenFile(const QString &path)
{
    qDebug("path:%s",qPrintable(path));
    if(!path.isNull())
    {
        QFile file(path);                       //建立QFile对象,只读方式打开
        if (!file.open(QIODevice::ReadOnly))
        {
            qDebug("打开文件失败!");
            return;
        }

        QTextStream in(&file);                      //建立文本流对象,与QFile对象file连接

        ui->plainTextEdit->setPlainText(in.readAll());           //将文件中所有内容读入编译器

        file.close();//关闭文本流
    }

    setWindowTitle("logPad - " + path);
}


//当用户放下这个文件后,就会触发dropEvent事件
void MainWindow::dropEvent(QDropEvent *e)
{
    if (!e->mimeData()->hasUrls())
    {
        return;
    }

    emit userDropFile(e->mimeData()->urls()[0].toLocalFile());//发送userDropFile信号
}

//当用户拖动文件到主窗口时候,就会触发dragEnterEvent事件
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{

    //判断拖拽文件类型,文件名 接收该动作
    if (event->mimeData()->hasFormat("text/uri-list"))
    {
        event->acceptProposedAction();
    }

}

四、原理说明

有空再补!

 

ref:

https://my.oschina.net/voler/blog/345722

https://blog.csdn.net/emdfans/article/details/45672679?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

https://blog.csdn.net/pcsuite/article/details/6147191

https://blog.csdn.net/a3631568/article/details/53819972

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值