title: Qt Multiple Line Text In Custom Delegate
body: <p>I have a custom delegate derived from QStyleOptionViewItem which is trying to draw multiline (wordwrap) a long line of text in the paint method. After doing some search and Qt doc reading, I looks like I need to use QTextLayout for such task, below is the code I have which still puts the text in one single line, any hints on how to wrapping the line around length of the QStyleOptionViewItem passed in? Thanks!!</p>
  
  <pre><code>void Delegate::paint(QPainter *painter,
                       const QStyleOptionViewItem &amp;option,
                       const QModelIndex &amp;index) const
  {
    painter-&gt;save();
  
    painter-&gt;translate(option.rect.topLeft());
  
    QString title = index.data(Qt::DisplayRole).toString();
    QTextLayout * layout = new QTextLayout(title, QApplication::font());
  
    layout-&gt;beginLayout();
    QTextLine line = layout-&gt;createLine();
    while (line.isValid()) {
      line.setLineWidth(option.rect.width());
      line = layout-&gt;createLine();
    }
   layout-&gt;endLayout();
    layout-&gt;draw(painter, QPointF(0, 0));
  
    painter-&gt;restore();
  }
  </code></pre>
  
  <p>Since I can't self answer, I will just post my findings here.
  I found couple issues with my code:</p>
  
  <ol>
  <li>The test string I are one word consisted of 200 characters and by default QTextLayout does word wrap. So I have to explicitly call QTextLayout::setWrapMode() for that test case to wrap.</li>
  <li>I am not setting position for each line. </li>
  </ol>
  
  <p>This is my paint method in Ruby:</p>
  
  <pre><code>def paint painter, styleOptionViewItem, modelIndex
    painter.save
    painter.translate styleOptionViewItem.rect.top_left
  
    marked_text = modelIndex.data(Qt::DisplayRole).value
    font = Qt::Application::font()
    text_layout = Qt::TextLayout.new marked_text
    text_layout.setFont font
  
    text_option = Qt::TextOption.new
    text_option.setWrapMode(Qt::TextOption::WrapAtWordBoundaryOrAnywhere)
    text_layout.setTextOption text_option
  
    text_layout.beginLayout
    fm = Qt::FontMetrics.new font
    font_height = fm.height
    i = 0
    while i&lt; LINE_LIMIT do
      line = text_layout.createLine
      break if (!line.isValid())
      line.setLineWidth(styleOptionViewItem.rect.width)
      line.setPosition(Qt::PointF.new(0, font_height * i))
      i += 1
    end
    text_layout.endLayout
    text_layout.draw painter, Qt::PointF.new(0, 0)
    painter.restore
  end
  </code></pre>