C++ 如何更改QTableView的标题背景色

C++ 如何更改QTableView的标题背景色,c++,qt,qtableview,qabstracttablemodel,C++,Qt,Qtableview,Qabstracttablemodel,以下是我目前尝试的内容。标题文本可以正确更改颜色,但背景不会更改为默认值 template<typename T> inline QVariant TableModel<T>::headerData(int section, Qt::Orientation orientation, int role) const { //... else if(role == Qt::BackgroundRole) { return QBrush(m_di

以下是我目前尝试的内容。标题文本可以正确更改颜色,但背景不会更改为默认值

template<typename T>
inline QVariant TableModel<T>::headerData(int section, Qt::Orientation orientation, int role) const
{
    //...
    else if(role == Qt::BackgroundRole) {
        return QBrush(m_display.headerBackground);
    }
    //...
}
模板
内联QVariant表格模型::headerData(int段,Qt::定向,int角色)常量
{
//...
else if(role==Qt::BackgroundRole){
返回QBrush(m_显示器,头部背景);
}
//...
}

如何设置背景色?

您可以在QTableView上设置样式表

ui->tableView->setStyleSheet("QHeaderView::section { background-color:red }");

有关更多信息,请参见这里的替代解决方案

MyTableView::MyTableView( QWidget* parent ) : QTableView( parent )
{
    ...
    // Make a copy of the current header palette.
    QPalette palette = horizontalHeader()->palette();

    // Set the normal/active, background color
    // QPalette::Background is obsolete, use QPalette::Window
    palette.setColor( QPalette::Normal, QPalette::Window, Qt::red );

    // Set the palette on the header.
    horizontalHeader()->setPalette( palette );
}

这个值是常量吗?每次在模型实例上调用这个函数时是否返回相同的画笔?如果没有,您是否发出相关信号通知视图标题数据已更改?此解决方案不适用于使用Qt 5.9.1的我,但样式表解决方案适用!这仍然使垂直和水平标题之间的“角”没有样式,这叫什么?它与表中的内容不同well@JimQTableView中的corner小部件作为QAbstractButton实现,可以使用“QTableView QTableCornerButton::section”选择器设置样式。(来自)