MCPcopy Create free account
hub / github.com/PlotJuggler/PlotJuggler / wrapLabelToWidth

Function wrapLabelToWidth

pj_widgets/src/MessageBox.cpp:54–78  ·  view source on GitHub ↗

Greedy word-wrap: insert '\n' so no single rendered line exceeds max_width. Returns text unchanged when it already fits on one line (the common case for short labels, which then render exactly as before). A single word wider than max_width is kept on its own line rather than dropped or split mid-word.

Source from the content-addressed store, hash-verified

52// short labels, which then render exactly as before). A single word wider than
53// max_width is kept on its own line rather than dropped or split mid-word.
54QString wrapLabelToWidth(const QString& text, const QFontMetrics& fm, int max_width) {
55 if (max_width <= 0 || fm.horizontalAdvance(text) <= max_width) {
56 return text;
57 }
58 const QStringList words = text.split(QLatin1Char(' '), Qt::SkipEmptyParts);
59 if (words.isEmpty()) {
60 return text;
61 }
62 // Greedily pack words onto the current line; start a new line when the next
63 // word would overflow. A single word wider than max_width still gets its own
64 // line (it just can't be packed with anything).
65 QStringList lines;
66 QString line = words.first();
67 for (int i = 1; i < words.size(); ++i) {
68 const QString candidate = line + QLatin1Char(' ') + words[i];
69 if (fm.horizontalAdvance(candidate) <= max_width) {
70 line = candidate;
71 } else {
72 lines.append(line);
73 line = words[i];
74 }
75 }
76 lines.append(line);
77 return lines.join(QLatin1Char('\n'));
78}
79
80} // namespace
81

Callers 1

rewrapButtonLabelsMethod · 0.85

Calls 4

horizontalAdvanceMethod · 0.80
isEmptyMethod · 0.45
sizeMethod · 0.45
appendMethod · 0.45

Tested by

no test coverage detected