6

I have a character pointer that in any run can have different length. For example:

char*  myChar;

In one run its content can be "Hi" and in another run it can be "Bye".

I want to copy the content of myChar to a QString, for example if I have:

QString myString;

I want to copy the content of myChar to myString; how can I do that?

NG_
  • 6,895
  • 7
  • 45
  • 67
TJ1
  • 7,578
  • 19
  • 76
  • 119
  • Why don't you use the Constructor ( QString myString(myChar) ) ? – TWE Oct 19 '12 at 13:57
  • Yes if mychar is null-terminated, juste use myString = myChar – gogoprog Oct 19 '12 at 13:58
  • I don't want the pointer to myString to be equal to the pointer to myChar. In part of the code I want copy the content of myChar to myString, but later when myChar changes I don't want that myString to be changed. – TJ1 Oct 19 '12 at 14:00
  • What? I was sure QString would make it's own copy of myChar. Is this an assumption or have you tested it? – andre Oct 19 '12 at 14:15
  • @gogoprog and ahenderson: you guys are right it make it's own copy. Thanks for the help. – TJ1 Oct 19 '12 at 14:30
  • It seems that although QString keeps its own copy of string, trying to access its byte array via toLocal8Bit().data() gives a pointer to the original string it's copied from, rather than the one it's holding. – syockit Jun 12 '20 at 06:48

1 Answers1

14

Use QString::fromLatin1(const char*), QString::fromLocal8Bit(const char*) or QString::fromUtf8(const char*) as appropriate. Note that you can't just copy the data because QStrings contain 16-bit Unicode characters. It will always need to decode the 8-bit representation.

Dan Milburn
  • 5,600
  • 1
  • 25
  • 18
  • @TJ1 It is written already. Take a look here: http://harmattan-dev.nokia.com/docs/library/html/qt4/qstring.html#fromUtf8 If you mean code: QString myString = QString::fromUtf8(myChar); – besworland Oct 19 '12 at 14:14
  • @besworland `myString` is a class variable that I have defined in my class definition somewhere else. so if I use the command that you showed doesn't it mean it is defined again and will be a local variable not my class variable? – TJ1 Oct 19 '12 at 14:29
  • Hmm.. Then just code: this->myString = QString::fromUtf8(myChar); :) – Joonhwan Oct 19 '12 at 15:20
  • @TJ1 Yes, in this case it will be defined once again. In your class you can simply assign any value to myString. – besworland Oct 22 '12 at 08:13