将QDir :: rootPath()更改为程序运行路径?

时间:2015-06-23 12:58:50

标签: c++ qt

我有一个Qt FTP服务器,它选择C:/作为根路径。我试图更改它以选择起始程序位置路径。

例如:如果ftpserver.exe位于H:/programs/ftpserver.exe,则必须自动将ftp根路径设置为H:/

代码:

ui->lineEditRootPath->setText(settings.value("settings/rootpath", QDir::rootPath()).toString());

代码:

void MainWindow::on_toolButtonBrowse_clicked()
{
    QString rootPath;
#ifdef Q_OS_ANDROID
    // In Android, the file dialog is not shown maximized by the static
    // function, which looks weird, since the dialog doesn't have borders or
    // anything. To make sure it's shown maximized, we won't be using
    // QFileDialog::getExistingDirectory().
    QFileDialog dialog;
    dialog.setAcceptMode(QFileDialog::AcceptOpen);
    dialog.setFileMode(QFileDialog::Directory);
    dialog.showMaximized();
    dialog.exec();
    if (!dialog.selectedFiles().isEmpty()) {
        rootPath = dialog.selectedFiles().front();
    }
#else
    rootPath = QFileDialog::getExistingDirectory(this, QString(), ui->lineEditRootPath->text());
#endif
    if (rootPath.isEmpty()) {
        return;
    }
    ui->lineEditRootPath->setText(rootPath);
}

void MainWindow::onPeerIpChanged(const QString &peerIp)
{
    ui->statusBar->showMessage("Connected to " + peerIp);
}

void MainWindow::on_pushButtonShowDebugLog_clicked()
{
    DebugLogDialog *dlg = new DebugLogDialog;
    dlg->setAttribute( Qt::WA_DeleteOnClose, true );
    dlg->setModal(true);
    dlg->showExpanded();
}

1 个答案:

答案 0 :(得分:1)

QCoreApplication::applicationDirPath()会返回您应用的确切目录路径,例如H:/programs,如果您的应用路径为H:/programs/ftpserver.exe 因此,如果您修改QString,则可以获得根目录。

例如:

QString rootPath = QCoreApplication::applicationDirPath(); 
rootPath.chop(rootPath.length() - 3); //we leave the 3 first characters of the path, the root folder)
ui->lineEditRootPath->setText(rootPath); 
settings.setValue("settings/rootpath", rootPath);