Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QString to char* conversion

I was trying to convert a QString to char* type by the following methods, but they don't seem to work.

//QLineEdit *line=new QLineEdit();{just to describe what is line here}

QString temp=line->text();
char *str=(char *)malloc(10);
QByteArray ba=temp.toLatin1();
strcpy(str,ba.data());

Can you elaborate the possible flaw with this method, or give an alternative method?

like image 308
mawia Avatar asked Mar 26 '10 13:03

mawia


3 Answers

Well, the Qt FAQ says:

int main(int argc, char **argv)
{
 QApplication app(argc, argv);
  QString str1 = "Test";
  QByteArray ba = str1.toLocal8Bit();
  const char *c_str2 = ba.data();
  printf("str2: %s", c_str2);
  return app.exec();
}

So perhaps you're having other problems. How exactly doesn't this work?

like image 61
Eli Bendersky Avatar answered Oct 24 '22 17:10

Eli Bendersky


Maybe

my_qstring.toStdString().c_str();

or safer, as Federico points out:

std::string str = my_qstring.toStdString();
const char* p = str.c_str();

It's far from optimal, but will do the work.

like image 66
davidnr Avatar answered Oct 24 '22 19:10

davidnr


The easiest way to convert a QString to char* is qPrintable(const QString& str), which is a macro expanding to str.toLocal8Bit().constData().

like image 62
Robert Avatar answered Oct 24 '22 19:10

Robert