您不需要样式表来执行此操作,styleshhet 并没有那么强大来完成开发人员想要的所有事情。使用更强大的东西——委托。我将向您展示主要思想和工作示例。标题:
#ifndef ITEMDELEGATEPAINT_H
#define ITEMDELEGATEPAINT_H
#include <QStyledItemDelegate>
class ItemDelegatePaint : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit ItemDelegatePaint(QObject *parent = 0);
ItemDelegatePaint(const QString &txt, QObject *parent = 0);
protected:
void paint( QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const;
QSize sizeHint( const QStyleOptionViewItem &option,
const QModelIndex &index ) const;
QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const;
void setEditorData(QWidget * editor, const QModelIndex & index) const;
void setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const;
void updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index) const;
signals:
public slots:
};
#endif // ITEMDELEGATEPAINT_H
这里有很多方法,但我只会向您展示绘画,因为它对您来说是最重要的。关于您可以在网络中找到的其他方法的说明
cp:
void ItemDelegatePaint::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QString txt = index.model()->data( index, Qt::DisplayRole ).toString();
if(index.row() == 0)//green row
painter->fillRect(option.rect,QColor(0,255,0));
else
if(index.row() == 1)//blue row
painter->fillRect(option.rect,QColor(0,0,255));
else
if(index.row() == 2)//red row
painter->fillRect(option.rect,QColor(255,0,0));
//and so on
if( option.state & QStyle::State_Selected )//we need this to show selection
{
painter->fillRect( option.rect, option.palette.highlight() );
}
QStyledItemDelegate::paint(painter,option,index);//standard processing
}
用法:
ui->tableView->setItemDelegate(new ItemDelegatePaint);
结果:
