vincent poortvliet
vincent poortvliet

Reputation: 97

QString variable changed to QCharRef when i use pointers in method

Hello everyone I am trying to get to know pointers better and I stumbled into a Qt type change. I have made a QString array and gave the pointer to the array to a method. But when I try to use a QString functions it give a error and says that it is a QCharRef which does not have the member function isEmpty().

The code:

QString data_array[2][3] =
{
 {"11:28:8","Room 1","Presence detected"},
 {"11:38:8","Room 1","No presence"}
}

bool method(QString *_data_array)   
{
 QString *data_array = _data_array;

 return data_array[0][1].isEmpty(); /* changed to QCharRef */
}

My question is why does this happen and how can I prevent it or change it?

Upvotes: 1

Views: 655

Answers (1)

Tmayto
Tmayto

Reputation: 135

The reason for which you are getting QCharRef is due to how QString is built. The [] operator returns one character from a QString (QString is built up from QChars, much like strings in C/C++ are character arrays). From the Qt documentation:

The return value is of type QCharRef, a helper class for QString. When you get an object of type QCharRef, you can use it as if it were a QChar &. If you assign to it, the assignment will apply to the character in the QString from which you got the reference.

So what that means for you is that when you use the lovely square bracket operators, you are no longer using a QString, you are using a QChar reference. As for how to change it, QChar's isNull() seems like it would fit your uses. so instead try return data_array[0][1].isNull(); and that should work.

I would also look into QStringList if you're doing things with lists of strings

Upvotes: 1

Related Questions