Search code examples
cssqtqt5qtablewidgetqtablewidgetitem

QTableWidget style per QTableWidgetItem


I'm using a simple QTableWidget to display some QTableWidgetItems, which look like this:

+-------------+-------------+
|             | some text 1 |
| some number +-------------+
|             | some text 2 |
+-------------+-------------+
|             | some text 1 |
| some number +-------------+
|             | some text 2 |
+-------------+-------------+

I know that I can draw a border around the QTableWidgetItems by setting a stylesheet for the QTableWidget like

QTableView::item {
    border-bottom: 1px solid black;
}

but this is applied for all the QTableWidgetItems. I'd like to draw the border only for the "some number" and "some text 2" items.

Is it possible to do so while sticking to the use of the QTableWidget and QTableWisgetItems? I can't use QObject::setProperty set some property to identify the items in the style sheet, because QTableWidgetItems are no QObjects …


Solution

  • use delegate, example

    class MyDelegate : public QItemDelegate
    {
      public:
        MyDelegate( QObject *parent ) : QItemDelegate( parent ) { }
        void paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const;
    };
    
    void MyDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const
    {
        QItemDelegate::paint( painter, option, index );
        painter->setPen( Qt::red );
        painter->drawLine( option.rect.topLeft(), option.rect.bottomLeft() );
       // What line should you draw
       // painter->drawLine( option.rect.topLeft(), option.rect.topRight() );
       // painter->drawLine( option.rect.topLeft(), option.rect.bottomLeft() );
    }
    ...
    
            m_TableWidgetClass->setItemDelegateForRow(row, new MyDelegate( this));
            //m_TableWidgetClass->setItemDelegateForColumn(column, new MyDelegate( this));