I'm new to QT so please excuse me if I'm blatantly doing something wrong here, but I've looked at all the questions here on the matter but can't seem to find something that works. I'm trying to have the user create a folder by entering a name for it, and it 'creates' a folder with the name. I say 'create' because it's not exactly creating one, it makes a folder first called "project" before you enter the name, and when you enter a name it renames it. However, when I try and rename the folder with the inputted name it gives me
error:C2664: 'int rename(const char *,const char *)' : cannot convert argument 1 from 'QString' to 'const char *'
Here's my code:
void MainWindow::on_actionNew_Project_triggered(const char *parameter)
{
//Create project folder
QString projectPath = "D:/Project";
QDir dir(projectPath);
if (!dir.exists()) {
dir.mkpath(projectPath);
}
//Get project name from user
bool result;
QString name = QInputDialog::getText(0, "New Project",
"Enter in project name", QLineEdit::Normal,
"", &result);
if(result && !name.isEmpty()) {
//Rename project folder to user created name
QDir dir(projectPath);
if (dir.exists()) {
rename(projectPath, name); //Gives me error HERE
}
}
}
I would appreciate it if you guys could help, I've been stuck on this for hours.
Try dir.rename(dir.dirName(), name);
You are trying to invoke a member function without an instance.
Since rename()
is a member function of QDir
, you need a QDir
instance in order to invoke it. So rather than just calling rename()
which invokes who knows what, you need to dir.rename()
.
QDir::rename()
actually takes 2 QString
s as parameters, but that other function you are invoking takes two raw strings, so you don't really need to convert the strings, you were just calling the wrong function.
bool QDir::rename(const QString & oldName, const QString & newName)
You are most likely calling rename()
from <stdio.h>
, which could also work given that the parameters are correct and the OS can rename the directory, in that case you will need to convert to "raw" C-style strings via yourString.toLatin1().constData()
. But since you are using Qt, you might as well use the QDir
API, which works directly with QString
.
If it still doesn't work, then either your input parameters are wrong, or there is something preventing the OS from rename the directory, for example a file currently in use.