是的,这是可能的!
如果您不想使用当前样式,您将不得不实现您自己的QStyledItemDelegate
(或),但不建议使用)。在那里你可以绘制任何你想要的(包括不同的选择颜色)。要使用模型的特殊功能,请使用自定义项目角色或将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);
//...
}
}
创建新的委托类的地方:
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
(至少在窗口中)。
对不起,我不太了解如何使用qitemdelegate,你能给我一个简短的例子,我如何在我的情况下实现它?谢谢(y) –
这看起来不错..我试过了,但我仍然有这个问题,当我点击时,像图标这样的复选框出现在我的单元格内。另外,当我切换我的选择时,当我点击其他地方时,已经选择的单元也会改变颜色。我的代码n的结果如图所示。 –
Table-> setItemDelegate(new HighlightDelegate(this));表 - >则setModel(网格); –