首页 > 解决方案 > 存在 StyleSheet 时如何使用 Qt::BackgroundRole 更改背景颜色

问题描述

我试图通过覆盖 Qt::BackgroundRole 的数据方法来设置 QTableView 项的背景颜色。

这在没有 StyleSheet 的情况下有效。

但是对于我设置 QTableView::item 边框属性的 qss,它不起作用。

我需要一些带有通用 StyleSheet 的 QTableView 和一个通过 Qt::DisplayRole 更改背景颜色的 QTableView。

但没有成功。

MyProxyModel 继承自 QStandardItemModel

class MyProxyModel : public QStandardItemModel
{
public:
     MyProxyModel(int in_row, int in_col);

    QVariant data(const QModelIndex &in_index, int in_role) const override;
};

然后我覆盖数据方法

QVariant MyProxyModel::data(const QModelIndex &in_index, int in_role) const
{
    if(Qt::BackgroundRole == in_role)
    {
        int tmp = QStandardItemModel::data(in_index, Qt::DisplayRole).toInt();

        switch (tmp)
        {
        case 1:
            return QVariant(QColor(0xBB, 0xFF, 0x99));
            break;
   ...
        default:

            break;
        }
    }

    return QStandardItemModel::data(in_index, in_role);
}

它可以在没有样式表的情况下工作。

但是使用 StyleSheet 它不起作用。



/*------------------------------------------*/
/*default*/
QTableView
{
    border: 1px solid #cccccc;
    background: #f3f3f3;
    color: #252424;
    font-family: "Segoe UI";
    outline: 0;
}

QTableView::item
{
/*    border-bottom: 1px solid #cccccc;     */  /* causes the bug */
}

/*------------------------------------------*/
/*second view*/
QTableView#SecondView
{
    background: #99dd99;
    border: 1px solid #cccccc;
    color: #252424;
    font-family: "Segoe UI";
    outline: 0;
}

QTableView#SecondView::item
{
/*    border: 0;    */                          /* causes the bug too */
}

标签: c++qtuser-interfaceqtstylesheets

解决方案


推荐阅读