Search code examples
qtqt4qtablewidget

HowTo draw border for QTableWidget row?


I'm trying to make a border for rows in QTableWidget with different ways, but all solutions don't respond my requirements. All that I want, is to draw a rectangle around a whole row. I had try QStyledItemDelegate class, but that is not my way, because delegates are used only for item[ row, column ], not for the whole rows or columns.

Here is wrong solution:

/// @brief Рисуем границу вокруг строки. 
class DrawBorderDelegate : public QStyledItemDelegate
{
public:
     DrawBorderDelegate( QObject* parent = 0 ) : QStyledItemDelegate( parent ) {}
     void paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const;

}; // DrawBorderDelegate

void DrawBorderDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
{
     QStyleOptionViewItem opt = option;

     painter->drawRect( opt.rect );

     QStyledItemDelegate::paint( painter, opt, index );  
}

And somewhere in code:

tableWidget->setItemDelegateForRow( row, new DrawBorderDelegate( this ) );

Thanks for help!


Solution

  • Your solution was not far wrong. You just need to be a bit more selective about which edges of the rectangle you draw:

    void DrawBorderDelegate::paint( QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index ) const
    {
         const QRect rect( option.rect );
    
         painter->drawLine( rect.topLeft(), rect.topRight() );
         painter->drawLine( rect.bottomLeft(), rect.bottomRight() );
    
         // Draw left edge of left-most cell
         if ( index.column() == 0 )
             painter->drawLine( rect.topLeft(), rect.bottomLeft() );
    
         // Draw right edge of right-most cell
         if ( index.column() == index.model()->columnCount() - 1 )
             painter->drawLine( rect.topRight(), rect.bottomRight() );
    
         QStyledItemDelegate::paint( painter, option, index );
    }
    

    Hope this helps!