Qt 如何将文件移动到另一个现有目录

How to move a file to another existing directory in Qt

我是 Qt 的初学者,我项目的一部分是将现有文件移动到另一个现有目录?有人可以给我一个具体的例子吗?我不确定是否应该使用 Qfile::rename()。我试着这样写

QDir::rename("/home/joshua/test.txt","/home/joshua/test/test_c.txt"); 

但是错误是不能调用没有对象的成员函数'bool QDir::rename(const QString&, const QString&)' QDir::rename("/home/joshua/test.txt","/home/joshua/test/test_c.txt"); ^

对不起大家,都是我的错,我问了一个如此不明确又如此愚蠢的问题,非常抱歉浪费了你们的时间,我是初学者,在我问这个问题之前,我真的真的没有注意到这个问题之前有人问过,因为我的水平太低了。因为我太天真,我不能再问了,所以请原谅我问这个问题,我压力太大,因为我在公司实习,我的项目对我来说很难,所以我没有选择这样做浪费你的时间,最后,我想对那些看过我问题的人说声谢谢。

根据 documentation:

bool QFile::rename(const QString &newName)

Renames the file currently specified by fileName() to newName. Returns true if successful; otherwise returns false.

对于您的情况,您必须执行以下操作:

QFile file("/home/joshua/test.txt");
file.rename("/home/joshua/test/test_c.txt");

QDir::rename()QDir 的一个实例方法,所以你需要一个 QDir 对象来调用它(这个目录将是传递文件名的基础)。对于您的示例,类似于:

QDir d("/home/joshua");
bool renamed = d.rename("test.txt" , "test/test_c.txt");

您将要使用 return 值。

或者,您可以使用 QFile::rename() - 默认目录是进程的当前工作目录。