QString to char *

Alec Jacobson

July 14, 2010

weblog/

I've been writing a lot in C++ lately and I am always so frustrated working with strings. Scripting languages like Ruby and Python make it so easy. Even Java/C# are a cinch. My latest problem has come from the handy Qt functions: getSaveFileName(...) and getOpenFileName(...). These were surprisingly easy to just drop in to my code. The only problem is that they return a QString. That's the thing about working in C++, everybody has to reinvent the string and you end up with a bagillion implementations that all have finicky details. I already had a function like this:
void write_data(char * file_name);
So what I needed was a way to turn the QString returned by getSaveFileName(...) into a char * so that I could pass it to my method. Here's how I did it:
QString file_name = QFileDialog::getSaveFileName(
  this,
  "Save data",
  "~",
  "Data (*.dat)");
if(obj_file_name.length() == 0){
  // Cancel button clicked in qt dialog
}else{
  write_data(file_name.toAscii().data());  
}
Any reason that I might run into trouble with the .toAscii() part?