Qt -如何复制文件与QFile::复制使用QFileDialog

Qt - How to copy file with QFile::copy using QFileDialog?

本文关键字:复制 QFile QFileDialog 文件 何复制 Qt      更新时间:2023-10-16
QString filename = QFileDialog::getOpenFileName(this,tr("Pdf files"), "C:/", "books(*.pdf)");

我想从QFileDialog中获得选中的文件并将其复制到我的桌面。我能用这样的东西吗?

QFile::copy(filename,"desktop");

您需要使用QStandardPaths获取到桌面的路径,然后在调用QFile::copy时使用该路径。

假设您希望在复制时保留文件名,您的代码将看起来像这样:

QString filePath = QFileDialog::getOpenFileName(this ,
                                                QObject::tr("Pdf files"),
                                                "C:/", "books(*.pdf)");
QFileInfo fi(filePath);
QString fileName= fi.fileName();
QString desktopPath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
QString destinationPath= desktopPath+QDir::separator()+fileName;
if(QFile::copy(filePath, destinationPath))
    qDebug() << "success";
else
    qDebug() << "failed";