Qt create Link between folders

2019-01-26 18:36发布

问题:

I have to build a small dialog that creates a symbolic link to a folder.

In windows I would use mklink /D command.

Is there a possibility to create such links in Qt? I have only seen QFile creating links between files and that they need to end with .lnk (http://qt-project.org/doc/qt-4.8/qfile.html#link) QDir on the other hand does not provide anything.

Any suggestions?

Best regards, Richard

回答1:

Is there a possibility to create such links in Qt?

Yes, it is, but only on Unix.

Unfortunately, this is not supported by QFile on Windows, not even by QDir. In my opinion, this would be a useful feature to submit a report for on the Qt Bug tracker.

The workaround would be to write something like this:

#ifdef Q_OS_UNIX
    QFile::link(sourceDir.absolutePath(), destDir.absolutePath());
#elif Q_OS_WIN
    QProcess process;
    process.start("mklink /D");

    // Wait for it to start
    if(!process.waitForStarted())
        return 0;

    bool retval = false;
    QByteArray buffer;
    while ((retval = process.waitForFinished()));
        buffer.append(process.readAll());

    if (!retval) {
        qDebug() << "Process error:" << process.errorString();
        qDebug() << "Output:" << buffer;
        return 1;
    }
#endif


回答2:

Just checked the documentation one more time. There is nothing but QFile::link() which creates a shortcut on Winddows. So, you need to execute mklink command with QProcess::execute().