0

我正在使用应用程序范围的样式表来改变我的 QTableView 的外观。同时,我希望某些列标题具有粗体文本,具体取决于标题文本。为此,我从QHeaderView派生并实现了paintSection函数:

class BoldHeaderView : public QHeaderView
{
    Q_OBJECT

public:
    BoldHeaderView( Qt::Orientation orientation, QWidget* parent = 0 ) : QHeaderView( orientation, parent ) { }

    void addBoldColumn( QString column_name )
    {
        if ( !m_bold_columns.contains( column_name ) )
            m_bold_columns.append( column_name );
    }

protected:
    void paintSection( QPainter* p_painter, const QRect& rect, int logicalIndex ) const
    {
        QFont bold_font = p_painter->font();
        QString column_name = model()->headerData( logicalIndex, Qt::Horizontal, Qt::DisplayRole ).toString();

        if ( m_bold_columns.contains( column_name ) )
            bold_font.setBold( true );

        p_painter->setFont( bold_font );

        QHeaderView::paintSection( p_painter, rect, logicalIndex );
    }

private:
    QList<QString> m_bold_columns;
};

然后我将其设置为 QTableView 的 Horizo​​ntalHeader :

BoldHeaderView* p_bold_header = new BoldHeaderView( Qt::Horizontal );
p_bold_header->addBoldColumn( "Foo" );

m_p_table_view->setHorizontalHeader( p_bold_header );

我的样式表如下所示:

QTableView QHeaderView::section {
    font-family: "Segoe UI";
    background-color: white;
    border-style: none;
}

它在主要功能中应用到整个应用程序:

QApplication app(argc, argv);
[...]
app.setStyleSheet( style_sheet );

感谢eyllanesc,我发现这与样式表冲突。粗体字体将始终被那里指定的任何内容覆盖。我需要找到一种方法来结合这两种方法。

4

1 回答 1

0

使用数据模型来负责那个怎么样?

如果数据的模型来源于 QAbstractItemModel,你可以改变它的 headerData 方法。就像是:

QVariant MyDerivedModel::headerData(int section, Qt::Orientation orientation, int role) const
{
   //... things

   if(role == Qt::FontRole) 
   {
      //if the column (the section) is one of the "special" ones, set it to bold
      //return the desired QFont in bold
   }

}
于 2017-09-22T11:53:49.957 回答