Last active
December 19, 2018 15:24
-
-
Save lethal-guitar/b9b55313eba00085590c to your computer and use it in GitHub Desktop.
Truncate string with ellipsis in the middle (Qt)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.