如何在QTableView中有不同的选择颜色?

时间:2015-11-19 16:52:53

标签: qt qtableview

是否也可以有两种不同的选择颜色?我该怎么做?你知道当你选择一个单元格时,可以使用样式表设置所选颜色,但由于我正在使用表视图,我想知道我的视图是否可以查询我的模型。例如,我有一个存储选择的变量。如果用户选择值“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( .... )
}

结果是我的单元格中有复选框的红色单元格。我不知道为什么会发生这种情况。我做错了吗?

1 个答案:

答案 0 :(得分:0)

是的,有可能!

如果您不想使用当前的样式,则必须实现自己的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(至少在窗口上)。