[Qt-interest] changing the way semected items of a QTableView do appear

TP paratribulations at free.fr
Wed Nov 10 23:51:00 CET 2010


> See also the attributes of QStyleOptionViewItem.
> A QStyleOptionViewItem is passed to QItemDelegate::paint().

Thanks a lot for your hint.
If it can help somebody, this is the paint() code of my custom delegate. It 
paints in white the cells of a QTableView, then it paints the hatch pattern 
defined in my model, and finally it draws the text in the default text 
color.
Is this the right way to do? Indeed, I am not really sure to have understood 
where the dark blue color of a selected item is set: if I comment out the 
line "qpainter.fillRect( rect, qbrush1 )", the dark blue color is still 
here. So if I am right, the dark blue color of a selected item is painted 
BEFORE this paint method of my delegate is called.

This is Python, but this could be understood by any Qt programmer.

Next step: surrounding the selected items of my model with a dotted frame.

####################

    def paint( self
            , qpainter
            , qstyleoptionviewitem
            , qmodelindex ):

        if qstyleoptionviewitem.state & QStyle.State_Selected:

            qpalette = QApplication.palette()
            # First brush: to paint the cell in the base() color, i.e.
            # white, instead of the selected state default color, i.e.
            # dark blue.
            qbrush1 = QBrush( Qt.SolidPattern )
            qbrush1.setColor( qpalette.base().color() )
            # Second brush: to paint the hatch pattern given by the
            # model, on the result of the first brush.
            qbrush2 = QBrush( qmodelindex.model().data( qmodelindex
                , Qt.BackgroundRole ) )

            # The rect for the solid white, and for the hatch pattern:
            rect = qstyleoptionviewitem.rect
            # And we finally get the text to display, in black.
            text = qmodelindex.model().data( qmodelindex ).toString()

            # This margin appears in QItemDelegate::textRectangle in Qt
            # source code.
            margin = QApplication.style().pixelMetric(
                    QStyle.PM_FocusFrameHMargin )+1
            rect_text = rect.adjusted( margin, 0, margin, 0 )

            qpainter.save()
            qpainter.fillRect( rect
                    , qbrush1 )
            qpainter.fillRect( rect
                    , qbrush2 )
            qpainter.setPen( qpalette.windowText().color() )
            qpainter.drawText(
                    rect_text
                    , Qt.AlignLeft | Qt.AlignVCenter
                    , text )
            qpainter.restore()
        else:
            super( QSqlItemDelegate, self ).paint(
                    qpainter
                    , qstyleoptionviewitem
                    , qmodelindex )




More information about the Qt-interest-old mailing list