Skip to content

Instantly share code, notes, and snippets.

@lethal-guitar
Last active December 19, 2018 15:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lethal-guitar/b9b55313eba00085590c to your computer and use it in GitHub Desktop.
Save lethal-guitar/b9b55313eba00085590c to your computer and use it in GitHub Desktop.
Truncate string with ellipsis in the middle (Qt)
#include <QString>
#include <cmath>
namespace {
const QString ELLIPSIS("...");
}
QString limitString(const QString& aString, int maxLength) {
if (aString.length() <= maxLength)
return aString;
float spacePerPart = (maxLength - ELLIPSIS.length()) / 2.0;
auto beforeEllipsis = aString.left(std::ceil(spacePerPart));
auto afterEllipsis = aString.right(std::floor(spacePerPart));
return beforeEllipsis + ELLIPSIS + afterEllipsis;
}
@bfloch
Copy link

bfloch commented Dec 19, 2018

Qt provides this out of the box: http://doc.qt.io/archives/qt-4.8/qfontmetricsf.html#elidedText
It is based on fontmetric not text length which might be more useful depending on the case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment