/// Calculate single line layout for given text with specified font. /// This function automatically add ellipsis text if the naural width /// is larger than given region. /// \layout The result layout. /// \font The font object. /// \string The text needs to be layouted. /// \align Alignment. /// \rect The region. /// \ellipsis Add ellipse to left or right if necessary. /// Returns the line height. int calculateSingleLineLayout(QTextLayout & layout, const QFont & font, const QString & string, const Qt::Alignment align, const QRect & rect, const Qt::TextElideMode ellipsis) { QFontMetrics fm(font); // Check if we need to add ellipsis. QString result_string = string; int width = ellipsisText(string, fm, rect.width(), ellipsis, result_string); // Construct the layout. layout.clearLayout(); layout.setCacheEnabled(false); layout.setText(result_string); layout.setFont(font); layout.beginLayout(); QTextLine line = layout.createLine(); if (line.isValid()) { line.setLineWidth(rect.width()); } layout.endLayout(); // Calculate the position. int x = rect.left(); int y = rect.top(); int h = static_cast<int>(line.height()); if (align & Qt::AlignHCenter) { x = ((rect.width() - width) >> 1) + x; }