Take the 2-minute tour ×

I'm trying to figure out the QString::lastIndexOf and QString::chop to delete a suffix off a file, so I can add one myself. However, I get weird output that doesn't make sense to me.

Here's my test code:

QString filename = "C:/Users/Ir77/Desktop/a.png";
qDebug() << "Filename is " << filename;
QString y = '.';
int x = filename.lastIndexOf(y, -1);
qDebug() << "Last index of . is " << x;
qDebug() << "filename is now " << filename;

And here's the qDebug() info that I get from it:

Filename is  "C:/Users/Ir77/Desktop/a.png" 
Last index of . is  23 
filename is now  "C:/U" 

I'm trying to only make it delete the ".png" at the end. I have no idea where the 23 comes from.

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

QString::chop() removes characters from the end of the string. "." is the 23rd (0-based) char, but calling chop() removes 23 characters and leaves you with "C:/U".


Had you considered using QFileInfo so that it does the work for you? (http://qt-project.org/doc/qt-4.8/qfileinfo.html) That'll give you a bunch of handy functions to get paths, portions of the filename, etc.

(I'm more familiar with Qt 4.8, but I'm assuming chop() hasn't changed in Qt 5.0.)

share|improve this answer
Yeah! Thanks allot. I didn't realize that the .lastIndexOf counts the QString from the start! And yeah, I ended up using QFileInfo as well! –  David Gentry Feb 16 '13 at 5:50
add comment

Your Answer


