c++ - 改变QDir::rootPath() 为程序运行路径?

标签 c++ qt

我有一个选择 C:/ 作为根路径的 Qt FTP 服务器。我正在尝试更改它以选择启动程序位置路径。

例如:如果 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();
}

最佳答案

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);

关于c++ - 改变QDir::rootPath() 为程序运行路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31003479/

相关文章:

c++ - 在 C++ 中的重载运算符中使用局部变量

c++ - 简单的 Qt 应用程序无法在 Mac OSX Yosemite 上打开

delphi - Qt 或 Delphi...如果您要选择其中之一?

c++ - GraphicsScene 中的轴承公式计算产生不稳定的结果

c++ - Boost asio-acceptor 在没有新连接的情况下解锁?

c++ - 如何使用命令行解析器库对类别中的选项进行分组?

c++ - .o/.a/.so 文件中到底有什么?

python - 如何在 PyQT 的辅助显示器上显示一个窗口?

qt - 在 QTreeView 中用鼠标悬停突出显示项目?

c++ - 使用 Boost ptree 将 JSON 数组解析为 std::string