Important: Please read the Qt Code of Conduct -

pyqt delegate text wrapping sizeHint and paint

  • 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?

    def sizeHint(self, option, index):
        size hint is being used to control text wrap of the definition.
        All columns are allowed to text wrap, but only definition is
        believed to need text wrapping.
        # set the sizeHint for all columns.
        if  index.isValid():
            fm = option.fontMetrics
            text = index.model().data(index)
            document = QtGui.QTextDocument()
            # change cell Width, height (One can add or subtract to change
            # the relative dimension).
            #return QtCore.QSize(QtSql.QSqlRelationalDelegate.sizeHint(self, option, index).width() + 200,
            # QtSql.QSqlRelationalDelegate.sizeHint(self, option, index).height() +200)
            return QtCore.QSize(document.idealWidth(), QtSql.QSqlRelationalDelegate.sizeHint(self, option, index).height())
        # Else the index is not valid and then return the base method.
            return super(ObjDelegate, self).sizeHint(option, index)
    def paint(self, painter, option, index):
        This will allow for text wrapping. The paint method will paint the text.
        if index.isValid():
            # This will highlight the selected cell.
            if option.state & QtGui.QStyle.State_Selected:
                painter.fillRect(option.rect, option.palette.highlight())
            # Get the text from the model.
            text = index.model().data(index)
            # Initialize the Qtextdocument.
            document = QtGui.QTextDocument()
            # settextwidth.
            ctx = QtGui.QAbstractTextDocumentLayout.PaintContext()
            # Save the painter. Saves the current painter state.
            # This is so that we can redraw it later.
            document.documentLayout().draw(painter, ctx)
            return super(ObjDelegate, self).paint(painter, option, index)