Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 更改Qt应用程序的当前路径_C++_Qt - Fatal编程技术网

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

C++ 更改Qt应用程序的当前路径,c++,qt,C++,Qt,我使用的是Qt库,我想将当前路径设置为QString oldConfigFileName中包含的路径,我使用的是setCurrent(),但setCurrent返回的值为false,表示更改路径失败。 代码: QString path=QDir::currentPath(); std::string currentpath=path.toStdString(); std::string configPath=oldConfigFileName.tostString(); bool res=QDi

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

QString path=QDir::currentPath();
std::string currentpath=path.toStdString();
std::string configPath=oldConfigFileName.tostString();
bool res=QDir::setCurrent(oldConfigFileName);
如果(res)
{

qDebug()在不知道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);
}
如果(!QDir(oldConfigFileName).exists())
{

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

QFileInfo fi(oldConfigFileName); 
bool res = QDir::setCurrent(fi.path());

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

qDebug()您似乎试图更改文件名的路径,
oldConfigFileName
的值是多少?QFileInfo-fi(oldConfigFileName);bool-res=QDir::setCurrent(fi.path());感谢drescherjm,它成功了。oldConfigFileName包含我的文件的路径,我想将当前路径设置到此位置。oldConfigFileName包含我的配置文件的路径,其值是正确的,因为configPath获得了正确的值。
if(res)
{
    qDebug() << "Path Changed";
}
else
{
    qDebug() << "Path not changed. Path string = " << oldConfigFileName;
}
QFileInfo fi(oldConfigFileName); 
bool res = QDir::setCurrent(fi.path());

if(res)
 {
    qDebug() << "Path Changed";
 }
else
{
  qDebug() << "Path not changed";
}