如何在 PyQt5 中具有预设样式表的 QTableView 中返回 QColor 作为 QBackgroundRole?

问题描述

我遇到了标题中提到的奇怪问题。

我有一个 QTableView。

self.table = QTableView()

然后给它设置一些 QSS。

self.table.setStyleSheet('''
QTableView {
    border: 2px solid red;
    padding: 5px;
    border-radius: 5px;
    gridline-color: red;
    color: red;
}
QTableView::item{
    border-color: none;
    padding-left: 5px;
    padding-right: 5px;
    gridline-color: rgb(44,49,60);
    border-bottom: 1px solid green;
}
QTableView::item:selected{
    background-color: blue;
}
''')

然后我尝试在模型中返回一个 QColor (QAbstractTableModel),但它不起作用。如果我删除了样式表,那么它就起作用了。有没有人是我 QSS 的哪一行造成了问题?

if role == Qt.BackgroundRole and index.row() == self.headStart:
            # Set header start color
            return QColor(208,74,2)

我需要样式表,同时我还需要 Qt.BackgroundRole 来工作。

解决方法

它看起来像一个 partially knownunresolved bug,当为 case 'UPDATE_LIST': return { ...state,list: action.payload,} 选择器指定背景颜色或边框时,颜色角色被忽略(因为它被样式表覆盖) .

一个可能的解决方案是设置一个项目委托并在调用默认实现之前填充底层矩形。

public class AuthorizationHeaderInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        LoginResponse toc = LoginResponse();
        Request request = chain.request()
                .newBuilder()
                .addHeader("Authorization","Bearer " + toc.getToken())
                .build();
        Response response = chain.proceed(request);
        return response;
    }
}

如果由于某些操作系统样式问题而无法正常工作,也请尝试为基本项目选择器设置 ::item