Qtableview set background color to some columns
-
While the answers above are perfectly valid I think in your case it might be easier to just use a delegate:
class BackgroundBrushDelegate : public QStyledItemDelegate{ Q_OBJECT Q_PROPERTY(QBrush backgroundBrush READ backgroundBrush WRITE setBackgroundBrush NOTIFY backgroundBrushChanged) Q_DISABLE_COPY(BackgroundBrushDelegate) public: explicit BackgroundBrushDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {} BackgroundBrushDelegate(const QBrush& brush, QObject *parent = nullptr) : QStyledItemDelegate(parent) , m_backgroundBrush(brush) {} const QBrush& backgroundBrush() const { return m_backgroundBrush; } void setBackgroundBrush(const QBrush& brush) { if(m_backgroundBrush==brush) return; m_backgroundBrush=brush; backgroundBrushChanged(m_backgroundBrush); } signals: void backgroundBrushChanged(const QBrush& brush); protected: void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const override { QStyledItemDelegate::initStyleOption(option,index); option->backgroundBrush = m_backgroundBrush; } private: QBrush m_backgroundBrush; }You can use it with
tableView->setItemDelegateForColumn(0,new BackgroundBrushDelegate(QBrush(Qt::yellow),tableView)); -
@VRonin Hi! I am trying to do something similar; however, I am building an application in python, not C++. Could you help me how to understand this code better so I can convert it to python? Or could you maybe show me how it would be in python?