更改Qt应用程序的当前路径

Changing current path of a Qt Application

本文关键字:当前路径 应用程序 Qt 更改      更新时间:2023-10-16

我正在使用Qt库,我想将当前路径设置为QString oldConfigFileName中包含的路径,我正在使用setCurrent(),但setCurrent返回一个错误值,表示更改路径失败。代码:

QString path = QDir::currentPath();
std::string currentpath  = path.toStdString();
std::string configPath = oldConfigFileName.toStdString();
bool res = QDir::setCurrent(oldConfigFileName);
if(res)
 {
    qDebug() << "Path Changed";
 }
else
{
  qDebug() << "Path not changed";
}

问题是您使用的路径是包含文件名的配置文件的完整路径。当您尝试将目录更改为此路径时,该命令将失败,因为oldConfigFileName是一个文件,而不是现有文件夹。解决此问题的一个简单方法是使用QFileInfo从路径中删除文件名部分,然后将其用作目录。

QFileInfo fi(oldConfigFileName); 
bool res = QDir::setCurrent(fi.path());
if(res)
 {
    qDebug() << "Path Changed";
 }
else
{
  qDebug() << "Path not changed";
}

在不知道oldConfigFileName的实际内容的情况下,失败的一个原因可能是路径不存在。在调用QDir::setCurrent()-方法之前,检查路径是否存在可能是个好主意。

if(!QDir(oldConfigFileName).exists())
{
    qDebug() << "Path does not exists.";
    // Path does not exists, if needed, it can be created by
    // QDir().mkdir(oldConfigFileName);
}

失败的另一个原因可能是oldConfigFileName不包含有效的路径字符串。为了检查这一点,我会按照以下方式更改调试日志:

if(res)
{
    qDebug() << "Path Changed";
}
else
{
    qDebug() << "Path not changed. Path string = " << oldConfigFileName;
}