1. 文档拖放 获取文件名

QT 实现拖放功能

 

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtGui>

class MainWindow : public QMainWindow
{
    Q_OBJECT
    
public:
    MainWindow(QWidget *parent = 0);

protected:
    void dragEnterEvent(QDragEnterEvent *event);
    void dropEvent(QDropEvent *event);

private:
    bool readFile(const QString &fileName);
    QTextEdit *textEdit;
};
#endif // MAINWINDOW_H

 

mainwindow.cpp

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    textEdit = new QTextEdit;
    setCentralWidget(textEdit);
    textEdit->setAcceptDrops(false);
    setAcceptDrops(true);
    setWindowTitle(tr("Drag test"));
}

void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
    if( event->mimeData()->hasFormat("text/uri-list") )
        event->acceptProposedAction();
}

void MainWindow::dropEvent(QDropEvent *event)
{
    QList<QUrl> urls = event->mimeData()->urls();
    if(urls.isEmpty())
        return;
    QString fileName = urls.first().toLocalFile();
    if(fileName.isEmpty())
        return;
    if(readFile(fileName))
        setWindowTitle(tr("%1-%2").arg(fileName).arg(tr("Drag File")));
}

bool MainWindow::readFile(const QString &fileName)
{
    bool r = false;
    QFile file(fileName);
    QTextStream in(&file);
    if( file.open(QIODevice::ReadOnly | QFile::Text) )
    {
        textEdit->setText(in.readAll());
        textEdit->append(fileName);
        r = true;
    }
    return r;
}


 

相关文章:

  • 2022-12-23
  • 2021-09-22
  • 2021-09-16
  • 2021-07-11
  • 2022-12-23
  • 2021-06-09
  • 2021-12-13
猜你喜欢
  • 2022-12-23
  • 2021-11-30
  • 2022-01-05
  • 2022-12-23
  • 2021-10-18
  • 2021-06-04
  • 2021-10-11
相关资源
相似解决方案