天天看點

Qt自定義Delegate

作者:音視訊開發老舅

1、實作一個自定義Delegate

這裡我們也來實作一個自定義Delegate,懷着了解Delegate的目的,主要實作以下幾個功能:

  1. 以不同顔色繪制View。
  2. 輕按兩下View方格區域彈出行編輯器,預設覆寫這個區域,顯示字母。
  3. 輸入行編輯器内的内容會被儲存,下次點開顯示。
  4. 滑鼠停留,顯示提示框。

2、繼承QAbstractItemDelegate

Qt提供了幾個标準的委托:

  1. QItemDelegate:Qt**曾經**預設使用的委托。
  2. QStyledItemDelegate。:**現在**預設使用的委托,官方推薦我們使用這個。(自從Qt 4.4)

為了熟悉委托借口,我們繼承虛基類QAbstractItemDelegate來實作我們的自定義委托。

3、實作虛函數

出去虛析構函數,QAbstractItemDelegate總共有9個虛函數,下面分别介紹。

paint()函數用來重繪view。我們這裡選擇用随機顔色填充背景::

void CustomeDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (!index.isValid() || option.state == QStyle::State_None || !index.isValid())
        return;

    painter->fillRect(option.rect, QColor(m_randomColor(m_generator)));
}
           

createEditor()和destroyEditor()的用途非常明顯,輕按兩下View的時候會彈出一個行編輯器:

QWidget* CustomeDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    return new QLineEdit(parent);
}

void CustomeDelegate::destroyEditor(QWidget *editor, const QModelIndex &index) const
{
    Q_ASSERT(dynamic_cast<QLineEdit*>(editor) != 0);

    delete dynamic_cast<QLineEdit*>(editor);
}
QT開發交流+赀料君羊:714620761           

helpEvent()表示幫助事件,當發生QEvent::ToolTip或者QEvent::WhatsThis事件的時候,就會調用這個函數,我們這裡根據事件不同顯示不同内容的Tool Tip:

bool CustomeDelegate::helpEvent(QHelpEvent *event, QAbstractItemView *view, const QStyleOptionViewItem &option, const QModelIndex &index)
{
    if (event->type() == QEvent::ToolTip) {
        QToolTip::showText(QCursor::pos(), QString("CustomeDelegate Tooltip"), reinterpret_cast<QWidget*>(view), option.rect, 1000);
    } else if (event->type() == QEvent::WhatsThis) {
        QToolTip::showText(QCursor::pos(), QString("CustomeDelegate Whatsthis"), reinterpret_cast<QWidget*>(view), option.rect, 1000);
    }
    return true;
}
           

當Editor顯示的時候,會調用setEditorData()這個函數來顯示預設的文字:

void CustomeDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    dynamic_cast<QLineEdit*>(editor)->setText(index.data(Qt::DisplayRole).toString());
}
QT開發交流+赀料君羊:714620761           

setModelData()這個函數用來更新Model中的資料:

void CustomeDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    model->setData(index, dynamic_cast<QLineEdit*>(editor)->text(), Qt::DisplayRole);
}
           

updateEditorGeometry()這個函數也會在Editor顯示的時候被調用,輕按兩下不同方格時,我們用它來更新編輯器的位置和大小:

void CustomeDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    dynamic_cast<QLineEdit*>(editor)->setFixedSize(option.rect.width(), option.rect.height());
    dynamic_cast<QLineEdit*>(editor)->move(option.rect.topLeft());
}
           

4、運作結果

Qt自定義Delegate

繼續閱讀