26 июня 2010

Стандартный делегат с возможностью дополнения.

Наследуемся от QStyledItemDelegate.
Заголовочный файл pgqueryitemdelegate.h
class PGQueryItemDelegate : public QStyledItemDelegate
{
  Q_OBJECT
  public:
  explicit PGQueryItemDelegate(QObject* parent = 0);

  QWidget* createEditor (QWidget* parent,
                         const QStyleOptionViewItem& option,
                         const QModelIndex& index ) const;

protected:
  virtual bool eventFilter(QObject *object, QEvent *event);
};
Файл реализации pgqueryitemdelegate.cpp
PGQueryItemDelegate::PGQueryItemDelegate(QObject* parent):QStyledItemDelegate(parent)
{
  setObjectName("pgQueryItemdelegate");
}

QWidget *PGQueryItemDelegate::createEditor(QWidget *parent,
                                           const QStyleOptionViewItem &option,
                                           const QModelIndex & index ) const
{
  QWidget *editor = QStyledItemDelegate::createEditor(parent, option, index);
  QLineEdit* lineEdit = qobject_cast(editor);
  if (lineEdit) {
    QMap<QString, int> values;
    QString itemData;
    int start = qMax(0, index.row() - 600);
    int end = qMin(index.model()->rowCount(index.parent()), index.row() + 600);
    for (int row = start; row < end; ++row) {
      itemData = index.model()->index(row, index.column(), index.parent()).data().toString();
      values.insert(itemData, index.row());
    }

    QCompleter* completer = new QCompleter(values.keys(), lineEdit);
    completer->setCompletionColumn(0);
    completer->setModelSorting(QCompleter::CaseSensitivelySortedModel);
    completer->setCompletionMode(QCompleter::InlineCompletion);
    lineEdit->setCompleter(completer);
    return lineEdit;
  }

  return editor;
}

bool PGQueryItemDelegate::eventFilter(QObject *object, QEvent *event)
{
  if (event->type() == QEvent::FocusIn) {
    QLineEdit *lineEdit = qobject_cast(object);
    if (lineEdit) {
      if (lineEdit->completer())
        lineEdit->completer()->setCompletionMode(QCompleter::PopupCompletion);
    }
  }
  if (event->type() == QEvent::FocusOut) {
    QLineEdit *lineEdit = qobject_cast(object);
    if (lineEdit) {
      QFocusEvent *focusEvent = static_cast(event);
      if (lineEdit->completer())
        if (qApp->activeWindow() == lineEdit->completer()->popup())
          return true;
    }
  }
  return QStyledItemDelegate::eventFilter(object, event);
}

Комментариев нет:

Отправить комментарий