1

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!

cbuchart
  • 10,847
  • 9
  • 53
  • 93
karan chavan
  • 215
  • 2
  • 12
  • And suppose you cut right through a letter, how are you supposed to partially display it? – a concerned citizen Aug 06 '18 at 06:15
  • @aconcernedcitizen I think that as the OP want a substring, the partial character problem is out of scope... in that case the method should either exceed the length adding a character or, probably the best way, omit it in order to fit the desired width – cbuchart Aug 06 '18 at 08:42

1 Answers1

0

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).

cbuchart
  • 10,847
  • 9
  • 53
  • 93
  • if I add Qt::ElideLeft it works , but i want it to be without ellipsis. Thanks! – karan chavan Aug 06 '18 at 13:22
  • @karanchavan interesting, it seems to be a bug or a discrepancy with documentation. I've added a workaround to it that will remove the ellipsis. Thanks for pointing this out, I've always used it with ellipsis ;) – cbuchart Aug 06 '18 at 13:27
  • @karanchavan, sorry, I've updated the code, copied the wrong version from tests – cbuchart Aug 06 '18 at 13:35