Search code examples
c++qtpixelqstringqfontmetrics

Get Substring of QString by Pixels in Qt cpp


I have a QString who's pixel length I can get by QFontmetrics::width(), also I can have character length from QString by QString::length(), but here I am intended to cut QString by specific amount of pixels.

Is there any way possible to have substring from QString by giving pixel size?

Thanks!


Solution

  • Yes, you can use QFontMetrics::elidedText to do so. For example, to cut at 200 pixels use:

    QString cutString = yourFontMetrics.elidedText(someString, Qt::ElideNone, 200);
    

    The second parameter indicates the cut mode (more values here).

    UPDATE: I'm not sure if it is a bug in Qt (Qt 5.10.0 for me), but indeed the Qt::ElideNone returns the same string. Here a workaround:

    QString cutString(const QString& str, const QFontMetrics& fm, int pixels)
    {
      const QChar ellipsis(0x2026);
      if (fm.width(str) <= pixels) return str;
      auto tmpStr = fm.elidedText(str, Qt::ElideRight, pixels + fm.width(ellipsis));
      return tmpStr.left(tmpStr.length() - 1);
    }
    

    A whole working example can be found here (you will need to add files to a new Qt project).