Hi Everyone,

I have a sqlrelationaltablemodel and a subclassed delegate how do you get text wrapping to work? Can you please explain the sizeHint and the paint method?

This is what I have so far, but no matter how much text is in the cell I only see two lines. Why is that? What am I missing?

Qt Code:
  1. def sizeHint(self, option, index):
  2. """
  3. size hint is being used to control text wrap of the definition.
  4. All columns are allowed to text wrap, but only definition is
  5. believed to need text wrapping.
  6. """
  7. # set the sizeHint for all columns.
  8. if index.isValid():
  9. fm = option.fontMetrics
  10. text = index.model().data(index)
  11. document = QtGui.QTextDocument()
  12. document.setDefaultFont(option.font)
  13. document.setPlainText(text.toString())
  14.  
  15. # change cell Width, height (One can add or subtract to change
  16. # the relative dimension).
  17. #return QtCore.QSize(QtSql.QSqlRelationalDelegate.sizeHint(self, option, index).width() + 200,
  18. # QtSql.QSqlRelationalDelegate.sizeHint(self, option, index).height() +200)
  19.  
  20. return QtCore.QSize(document.idealWidth(), QtSql.QSqlRelationalDelegate.sizeHint(self, option, index).height())
  21.  
  22. # Else the index is not valid and then return the base method.
  23. else:
  24. return super(ObjDelegate, self).sizeHint(option, index)
  25.  
  26.  
  27. def paint(self, painter, option, index):
  28. """
  29. This will allow for text wrapping. The paint method will paint the text.
  30. """
  31. if index.isValid():
  32. # This will highlight the selected cell.
  33. if option.state & QtGui.QStyle.State_Selected:
  34. painter.fillRect(option.rect, option.palette.highlight())
  35.  
  36. # Get the text from the model.
  37. text = index.model().data(index)
  38.  
  39. # Initialize the Qtextdocument.
  40. document = QtGui.QTextDocument()
  41. document.setPlainText(text.toString())
  42. document.setDefaultFont(option.font)
  43.  
  44. # settextwidth.
  45. document.setTextWidth(option.rect.width())
  46.  
  47. ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
  48.  
  49. # Save the painter. Saves the current painter state.
  50. # This is so that we can redraw it later.
  51. painter.save()
  52. painter.translate(option.rect.topLeft())
  53. document.documentLayout().draw(painter, ctx)
  54. painter.restore()
  55.  
  56. else:
  57. return super(ObjDelegate, self).paint(painter, option, index)
To copy to clipboard, switch view to plain text mode