Qt Header on QListView Implementation of the custom QListView


QSize MainMenuListView::Header::sizeHint() const
    // fontmetrics() allows to get the default font size for the widget.
    return QSize(menu->headerAreaWidth(), fontMetrics().height());

void MainMenuListView::Header::paintEvent(QPaintEvent* event)
    // Catches the paint event in the parent.

MainMenuListView::MainMenuListView(QWidget* parent, const QString& header) : QListView(parent), headerText(header)
    headerArea = new Header(this);

    // Really important. The view port margins define where the content
    // of the widget begins.
    setViewportMargins(0, fontMetrics().height(), 0, 0);

void MainMenuListView::headerAreaPaintEvent(QPaintEvent* event)
    // Paints the background of the header in gray. 
    QPainter painter(headerArea);
    painter.fillRect(event->rect(), Qt::lightGray);

    // Display the header title in black.

    // Writes the header aligned on the center of the widget. 
    painter.drawText(0, 0, headerArea->width(), fontMetrics().height(), Qt::AlignCenter, headerText);

int MainMenuListView::headerAreaWidth()
    return width();

void MainMenuListView::resizeEvent(QResizeEvent* event)
    // Executes default behavior.
    // Really important. Allows to fit the parent width.