QListView不使用委托的大小提示

时间:2011-08-02 16:14:15

标签: qt user-interface listview delegates model-view

我有一个呈现自定义项代理的QListView。我正在覆盖委托的sizeHint()来提供大小,但似乎列表视图没有考虑到这一点。以下是我正在使用的代码:

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();
}

这就是我使用它的方式:

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

项目在列表视图中正确显示,但永远不会调用sizeHint()(我已将调试语句添加到要检查的调用中),因此项目的大小不正确。任何人都可以看到可能出现的问题吗?

1 个答案:

答案 0 :(得分:3)

这是因为签名不匹配。您在签名结束时错过了const(滚动代码)。

应该是

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