是否也可以有两种不同的选择颜色?我该怎么做呢?您知道,当您选择一个单元格时,可以使用样式表来设置选定的颜色,但是由于我使用的是表视图,所以我想知道我的视图是否可以查询我的模型。例如,我有一个变量来存储所选内容。如果用户选择一个值"1",当他选择一个单元格时,它将是红色,当他选择"2“形成下拉列表时,当他选择该单元格时,它将是蓝色的。这有可能吗?(我的表将同时显示两种不同的选定单元格颜色,因为不同的颜色应该有不同的含义)。
我有下面的代码,但是它返回一个奇怪的结果。
我的data()函数:
if (role == Qt::DisplayRole)
{
Return data[row][col];
}
Else if (role = Qt::DecorationRole)
{
//if ( selectionVar == 0 )
return QVariant(QColor(Qt::red));
//else if( .... )
}其结果是,我在单元格中有了带有复选框的红细胞。我不知道为什么会这样。我做错什么了吗?
发布于 2015-11-19 17:52:47
是的,这是可能的!
如果不想使用当前的样式,则必须实现自己的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);
//...
}
}在某个地方创建新的委托类:
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);
}...and告诉视图使用委托:
this->ui->itemView->setItemDelegate(new HighlightDelegate(this));就这样!这个(如您所见)是使用QItemDelegate创建的。用QStyledItemDelegate创建它似乎是不可能的,因为它将忽略QPalette::Highlight (至少在windows上)。
https://stackoverflow.com/questions/33809845
复制相似问题