简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM