2015-11-19 107 views
0

也有可能有两种不同的选择颜色?我该怎么做?你知道当你选择一个单元格时,可以使用样式表设置选定的颜色,但是因为我使用的是表格视图,所以我想知道我的视图是否可以查询我的模型。例如,我有一个变量来存储选择。如果用户选择一个值“1”,当他选择一个单元格时它将是红色,当他从下拉列表中选择“2”时,当他选择单元格时它将是蓝色的。这可能吗?(我的表格将同时显示两种不同的选定单元格颜色,因为不同的颜色应该有不同的含义)。如何在QTableView中有不同的选择颜色?

我有下面的代码,但它返回一个奇怪的结果。

我的数据()函数:

if (role == Qt::DisplayRole) 
{ 
Return data[row][col]; 
} 
Else if (role = Qt::DecorationRole) 
{ 
//if (selectionVar == 0) 
return QVariant(QColor(Qt::red)); 
//else if(....) 
} 

的结果是,我在细胞中红细胞与复选框。我不知道为什么会这样。难道我做错了什么?

回答

0

是的,这是可能的!

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

+0

对不起,我不太了解如何使用qitemdelegate,你能给我一个简短的例子,我如何在我的情况下实现它?谢谢(y) –

+0

这看起来不错..我试过了,但我仍然有这个问题,当我点击时,像图标这样的复选框出现在我的单元格内。另外,当我切换我的选择时,当我点击其他地方时,已经选择的单元也会改变颜色。我的代码n的结果如图所示。 –

+0

Table-> setItemDelegate(new HighlightDelegate(this));表 - >则setModel(网格); –