更改Qt应用程序的当前路径
Changing current path of a Qt Application
我正在使用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;
}
相关文章:
- 更改应用程序数据的路径
- CMake导出的库-在客户端应用程序中找不到include/Lib路径
- 用于检索当前正在使用的应用程序的函数
- 按名称问题获取卸载应用程序路径
- 检查任务栏中的当前应用程序吗?(C ,Windows API)
- QT MAC应用程序存储数据路径
- Qt 显示应用程序(如果当前正在运行)
- 如何将应用程序URI转换为普通文件路径
- 如何使用QT程序中的默认应用程序打开使用相对路径的PDF
- 当我想扩展当前应用程序的功能时,出现DIAMOND情况
- 在UWP中获取fopen()的应用程序路径
- 在应用程序末尾获取不带应用程序名称的应用程序路径
- 在C++中设置正在运行的应用程序的当前目录
- 获取dll中的应用程序路径
- 服务器应用程序看不到具有相对路径的文件
- 打开.doc文件,但不提供其处理程序应用程序C++的路径
- 如何使用Qt Windows中的设置路径属性从命令行运行应用程序(.exe)时在命令行上打印日志
- 打开外部应用程序并关闭当前应用程序
- Windows 应用程序在以非管理员身份运行时看到旧版本的文件而不是当前版本
- 更改Qt应用程序的当前路径