Ulisses Santos Ulisses Santos - 1 year ago 284
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
and copy it to my desktop. Can I use something like this?


Answer Source

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";
    qDebug() << "failed";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download