Ulisses Santos Ulisses Santos - 3 months ago 29
C++ Question

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

QString filename = QFileDialog::getOpenFileName(this,tr("Pdf files"), "C:/", "books(*.pdf)");


I want to get the selected file from
QFileDialog
and copy it to my desktop. Can I use something like this?

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

Answer

You need to get the path to the desktop using QStandardPaths, and then use that path in your call to QFile::copy.

Assuming you want to preserve the file name while copying, your code will look something like this:

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";
Comments