您必须使用自定义委托。子类化QStyledItemDelegate
并实现它的paint()
方法,如下所示:
void MyDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
QStyleOptionViewItem itemOption(option);
initStyleOption(&itemOption, index);
if ((itemOption.state & QStyle::State_Selected) &&
(itemOption.state & QStyle::State_Active))
itemOption.palette.setColor(QPalette::Highlight, Qt::red); // set your color here
QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &itemOption, painter, nullptr);
}
如果你想从模型中获得你的选择颜色,我建议为此目的定义一个特殊的自定义角色:
enum MyRoles
{
HighlightColorRole = Qt::UserRole
};
您的模型将使用此角色通过该方法返回您的自定义突出显示(选择)颜色QAbstractItemModel::data()
。
在您的委托中,您可以像这样获得该颜色:
QColor color = index.data(HighlightColorRole).value<QColor>();