是的,有可能!
您必须实现自己的QStyledItemDelegate(或QItemDelegate,如果您不想使用当前样式。但不建议这样做)。在那里你可以画任何你想要的东西(包括不同的选择颜色)。要使用模型的特殊功能,请使用自定义项目角色或将 QModelIndex::model() 转换为您自己的模型实现。 (如果需要更多详细信息,我可以发布更多)
编辑一个简单的例子:
在你的模型中做:
QVariant MyModel::data(const QModelIndex &index, int role) const
{
switch(role) {
//...
case (Qt::UserRole + 3)://as an example, can be anything greater or equal to Qt::UserRole
return (selectionVar == 0);
//...
}
}
在某处创建新的 Delegate 类:
class HighlightDelegate : public QItemDelegate //QStyledItemDelegate would be better, but it wasn't able to change the styled highlight color there
{
public:
HighlightDelegate(QObject *parent);
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const Q_DECL_OVERRIDE;
};
HighlightDelegate::HighlightDelegate(QObject *parent) :
QItemDelegate(parent)
{}
void HighlightDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItem opt = option;
if(index.model()->data(index, Qt::UserRole + 3).toBool())//same here
opt.palette.setColor(QPalette::Highlight, Qt::red);
this->QItemDelegate::paint(painter, opt, index);
}
...并告诉视图使用委托:
this->ui->itemView->setItemDelegate(new HighlightDelegate(this));
就是这样!这个(如您所见)是使用QItemDelegate 创建的。用QStyledItemDelegate 创建它似乎是不可能的,因为它会忽略QPalette::Highlight(至少在Windows 上)。