日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

QT實現多文件拖拽獲取路徑的方法_C 語言

作者:Jason~shen ? 更新時間: 2022-09-30 編程語言

本文實例為大家分享了QT實現多文件拖拽獲取路徑的具體代碼,供大家參考,具體內容如下

功能

將多個文件拖拽進界面中,顯示文件的路徑。

實現

1、啟用窗體放下操作

this->setAcceptDrops(true);//啟用放下操作

2、重寫dragEnterEvent()函數,用于篩選拖拽事件

void dragEnterEvent(QDragEnterEvent *e);

void MainWindow::dragEnterEvent(QDragEnterEvent *e)
{
? ? //對拖放事件進行篩選
? ? if (true)
? ? {
? ? ? ? e->acceptProposedAction();?? ?//放行,否則不會執行dropEvent()函數
? ? }
}

3、重寫dropEvent()函數,用于處理拖拽事件

void dropEvent(QDropEvent *e);

void MainWindow::dropEvent(QDropEvent *e)
{
? ? QList<QUrl> urls = e->mimeData()->urls();
? ? if(urls.isEmpty())
? ? ? ? return ;
? ? qDebug()<< urls.size();
? ? foreach (QUrl u, urls)
? ? {
? ? ? ? QString filepath = u.toLocalFile();
? ? ? ? pathlist.append(filepath);
? ? }
}

4、重復文件去除

QList存儲文件路徑,由于Qset是沒有重復項的,故可先轉換為set,再轉回為list即可。

pathlist = pathlist.toSet().toList();

效果

UI布局

最后效果

源碼

頭文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
?
#include <QMainWindow>
#include <QTextEdit>
?
namespace Ui {
class MainWindow;
}
?
class MainWindow : public QMainWindow
{
? ? Q_OBJECT
?
public:
? ? explicit MainWindow(QWidget *parent = 0);
? ? ~MainWindow();
?
protected:
? ? void dragEnterEvent(QDragEnterEvent *e);
? ? void dropEvent(QDropEvent *e);
?
private slots:
? ? void on_pushButton_upload_clicked();
?
private:
? ? Ui::MainWindow *ui;
? ? QList<QString> pathlist;
};
?
#endif // MAINWINDOW_H

源文件

#include "mainwindow.h"
#include "ui_mainwindow.h"
?
#include <QDragEnterEvent>
#include <QFile>
#include <QDebug>
#include <QMimeData>
MainWindow::MainWindow(QWidget *parent) :
? ? QMainWindow(parent),
? ? ui(new Ui::MainWindow)
{
? ? ui->setupUi(this);
?
? ? ui->textEdit->setAcceptDrops(false); //禁用控件的放下操作
? ? this->setAcceptDrops(true);//啟用放下操作
}
?
MainWindow::~MainWindow()
{
? ? delete ui;
}
?
void MainWindow::dragEnterEvent(QDragEnterEvent *e)
{
? ? //對拖放事件進行篩選
? ? if (true)
? ? {
? ? ? ? e->acceptProposedAction();?? ?//放行,否則不會執行dropEvent()函數
? ? }
}
?
void MainWindow::dropEvent(QDropEvent *e)
{
? ? QList<QUrl> urls = e->mimeData()->urls();
? ? if(urls.isEmpty())
? ? ? ? return ;
? ? qDebug()<< urls.size();
? ? foreach (QUrl u, urls)
? ? {
? ? ? ? QString filepath = u.toLocalFile();
? ? ? ? pathlist.append(filepath);
? ? }
? ? //去掉重復路徑
? ? pathlist = pathlist.toSet().toList();
? ? ui->textEdit->clear();
? ? for(int i=0;i<pathlist.size();++i)
? ? {
? ? ? ? QString path = pathlist.at(i);
? ? ? ? ui->textEdit->append(path);
? ? }
}
?
?
void MainWindow::on_pushButton_upload_clicked()
{
? ? qDebug()<<pathlist;
}

原文鏈接:https://blog.csdn.net/qq_40602000/article/details/104719164

欄目分類
最近更新