如何在QTableView中修改标题字体大小 - 特定于OSX

时间:2015-05-07 21:28:24

标签: macos qt fonts qt5 qtableview

我正在尝试修改Mac OSX 10.9.5上Qt5.4.0中由QTableView填充的QAbstractTableModel的行标题和列标题中使用的字体大小。

更新:这似乎是一个特定于OSX的问题,因为我可以使用Qt5.4.0在CentOS 6.2 Linux上运行以下所有三个实验,它们都可以正常工作,产生预期的字体大小变化。

为简洁起见,我将在下面的示例代码中包含我已完成的所有三个实验[其中一些受StackOverflow和其他博客帖子的启发...],标记并注释掉了:

#include <QApplication>
#include <QMainWindow>
#include <QtGui>
#include <QAbstractTableModel>
#include <QTableView>
#include <QHeaderView>

class TestModel : public QAbstractTableModel
{
    public:
                        TestModel() {};
                        ~TestModel() {};

            int         rowCount( const QModelIndex& parent = QModelIndex() ) const;
            int         columnCount( const QModelIndex& parent = QModelIndex() ) const;
            QVariant    data( const QModelIndex& index, int role ) const;
            QVariant    headerData( int section, Qt::Orientation orientation, int role ) const;

};

int
TestModel::rowCount( const QModelIndex& index ) const {
    return 5;
}

int
TestModel::columnCount( const QModelIndex& index ) const {
    return 5;
}

QVariant
TestModel::data( const QModelIndex& index, int role = Qt::DisplayRole ) const {

    switch( role ) {
    case( Qt::DisplayRole ):
            return( QString( "%1,%2" ).arg( index.row() ).arg( index.column() ) );
    default:
            return QVariant();
    }
}

QVariant
TestModel::headerData( int section, Qt::Orientation orientation, int role ) const {
    QFont   font;

    switch( role ) {
    case( Qt::DisplayRole ):
            if( orientation == Qt::Horizontal ) {
                    return( QString( "Column %1" ).arg( section ) );
            } else {
                    return( QString( "Row %1" ).arg( section ) );
            }
    // EXPERIMENT #3:
    // case( Qt::FontRole ):
    //      font.setPointSize(48);
    //      return font;
    default:
            return QVariant();
    }
}

int
main( int argc, char *argv[] ) {
    QApplication app( argc, argv );

    TestModel* model = new TestModel();

    QMainWindow* mw = new QMainWindow();

    QTableView* tableView = new QTableView();

    tableView->setModel( model );

    // EXPERIMENT #1:
    // QFont font;
    // font = tableView->horizontalHeader()->font();
    // font.setPointSize(48);
    // tableView->horizontalHeader()->setFont( font );

    // EXPERIMENT #2:
    // tableView->horizontalHeader()->setStyleSheet("QHeaderView { font-size: 48pt; }");

    mw->setCentralWidget( tableView );

    mw->show();

    return app.exec();
}

当我在没有任何字体更改尝试或使用EXPERIMENT#1或EXPERIMENT#2的情况下运行时,我会得到以下结果:

No EXPERIMENT, or EXPERIMENT #1, or EXPERIMENT #2 result

请注意,在EXPERIMENT#1和#2结果中,列和行标题的字体大小没有改变,这与我的希望相反。当我在启用EXPERIMENT#3的情况下运行代码时,我仍然没有对列/行标题的字体大小进行任何更改,但我确实得到了一个奇怪的效果,即列标题框的大小适合较大的字体:

EXPERIMENT #3 result

我的偏好是让实验#1的变体起作用,这样可以更好地与真实代码协调。

如何成功更改QTableView行和列标题的字体大小?

0 个答案:

没有答案