【问题标题】:How to change the header background color of a QTableView如何更改 QTableView 的标题背景颜色
【发布时间】:2012-07-12 08:55:47
【问题描述】:

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

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);
    }
    //...
}

如何设置背景颜色?

【问题讨论】:

  • 这个值是常量吗——每次在模型实例上调用这个函数时是否返回相同的画笔?如果没有,您是否发出相关信号通知视图标题数据已更改?

标签: c++ qt qtableview qabstracttablemodel


【解决方案1】:

可以在QTableView上设置样式表

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

更多信息见http://doc.qt.io/qt-4.8/stylesheet-examples.html

【讨论】:

  • 这仍然使垂直和水平标题之间的“角”没有样式,这叫什么?它与表格内容不同
  • @Jim QTableView 中的角小部件实现为 QAbstractButton,可以使用“QTableView QTableCornerButton::section”选择器设置样式。 (来自doc.qt.io/qt-5/stylesheet-reference.html#qtableview-widget
【解决方案2】:

这是另一种解决方案。

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,但样式表解决方案可以!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多