QT 实现拖放功能
1. 文档拖放 获取文件名
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; }