你不需要樣式表來做到這一點,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
這裏有很多方法,但我會告訴你只有油漆,因爲它是你最重要的事情。關於另一個方法說明,你可以找到在web
CPP:
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);
結果:
謝謝,這就是我一直在尋找的東西。它的工作原理! – klasyc 2014-12-10 08:18:46