【问题标题】:How to have different selection color in QTableView?如何在 QTableView 中有不同的选择颜色?
【发布时间】:2015-11-19 16:52:53
【问题描述】:

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

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

我的数据()函数:

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

结果是我有红色单元格,单元格中有复选框。我不知道为什么会这样。我是不是做错了什么?

【问题讨论】:

    标签: qt qtableview


    【解决方案1】:

    是的,有可能!

    您必须实现自己的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(至少在Windows 上)。

    【讨论】:

    • 对不起,我不太明白如何使用 qitemdelegate,你能举一个简短的例子,我该如何在我的情况下实现它?谢谢(y)
    • 看起来不错.. 我试过了,但我仍然遇到这个问题,当我单击时,我的单元格中会出现类似复选框的图标。此外,当我切换我的选择时,当我点击其他地方时,已经选择的单元格也会改变颜色。我的代码n结果如图..
    • Table->setItemDelegate(new HighlightDelegate(this)); Table->setModel(grid);
    猜你喜欢
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 2012-06-13
    • 2022-07-16
    • 2023-04-07
    • 2020-05-11
    相关资源
    最近更新 更多