【问题标题】:How to display bold text in a specific QHeaderView section in combination with a stylesheet如何结合样式表在特定的 QHeaderView 部分中显示粗体文本
【发布时间】:2018-03-03 22:49:51
【问题描述】:

我正在使用应用程序范围的样式表来改变我的 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,我发现这与样式表冲突。粗体字体将始终被那里指定的任何内容覆盖。我需要找到一种方法来结合这两种方法。

【问题讨论】:

  • 我测试了你的代码,它工作正常
  • 这很奇怪。我忽略了我使用应用程序范围的样式表这一事实。我将禁用它们并再次测试。
  • 是的,样式表似乎是个问题。我正在更新问题。
  • 展示如何应用样式表的示例。
  • 正如我所说,我添加了以下样式:"QHeaderView::section {" "background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #616161, stop: 0.5 #505050, stop: 0.6 #434343, stop:1 #656565);" "color: white;" "padding-left: 4px;" "border: 1px solid #6c6c6c;" "}" 和作品:imgur.com/a/Eik1K,请参阅名字和 id

标签: qt qpainter qheaderview


【解决方案1】:

使用数据的模型来负责呢?

如果数据的模型来源于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
   }

}

【讨论】:

  • 我将不得不尝试这是否与样式表冲突。谢谢你的想法。
  • 知道如何访问标题的当前字体吗?
  • 如果您没有更改默认设置,您可以使用 { QFont boldFont; boldFont.setBold(true);返回粗体字; }
  • @pablo_worker 该字体是系统的字体,不是分配样式表的字体
  • 是的,我需要将我的“boldFont”基于已经改变的字体。
猜你喜欢
  • 2016-05-25
  • 1970-01-01
  • 2019-05-03
  • 2015-12-29
  • 2022-01-20
  • 2013-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多