Search code examples
qtuser-interfacelistviewdelegatesmodel-view

QListView doesn't use size hint of delegate


I have a QListView that renders custom item delegates. I am overriding sizeHint() of the delegate to provide the size but it seems the list view doesn't take this into account. Below is the code I'm using:

CardItemDelegate.h

#ifndef CARDITEMDELEGATE_H
#define CARDITEMDELEGATE_H

class CardItemDelegate : public QStyledItemDelegate {

    Q_OBJECT

public:

    explicit CardItemDelegate(QObject *parent = 0);
    QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index);
    void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;

};

#endif // CARDITEMDELEGATE_H

CardItemDelegate.cpp

#include "CardItemDelegate.h"

CardItemDelegate::CardItemDelegate(QObject *parent) : QStyledItemDelegate(parent) {

}

QSize CardItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) {
    qDebug() << "size hint called";
    return QSize(100, 30);
}

void CardItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
    painter->save();

    painter->setBrush(Qt::green);
    painter->setPen(Qt::red);
    painter->drawRect(option.rect);

    painter->restore();
}

And this is how I'm using it:

DeckListModel* model = new DeckListModel();
ui->deckListView->setModel(model);
ui->deckListView->setItemDelegate(new CardItemDelegate());

The items are displayed properly in the list view however sizeHint() is never called (I've added a debug statement to the call to check) so the items don't have the right size. Can anybody see what could be the issue?


Solution

  • it's because of signature mismatch. You missed const at the end of the signatute (scroll code).

    Should be

    QSize CardItemDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
                                                                                                       //^^^^^ - here