summaryrefslogtreecommitdiffstats
path: root/src/widgets/itemviews/qstyleditemdelegate.cpp
blob: b5fc8d7d63cd917eb79266c27c3583be67d91f03 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWidgets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qstyleditemdelegate.h"

#ifndef QT_NO_ITEMVIEWS
#include <qabstractitemmodel.h>
#include <qapplication.h>
#include <qpa/qplatformintegration.h>
#include <qpa/qplatformdrag.h>
#include <private/qguiapplication_p.h>
#include <qbrush.h>
#include <qlineedit.h>
#include <qtextedit.h>
#include <qplaintextedit.h>
#include <qpainter.h>
#include <qpalette.h>
#include <qpoint.h>
#include <qrect.h>
#include <qsize.h>
#include <qstyle.h>
#include <qdatetime.h>
#include <qstyleoption.h>
#include <qevent.h>
#include <qpixmap.h>
#include <qbitmap.h>
#include <qpixmapcache.h>
#include <qitemeditorfactory.h>
#include <private/qitemeditorfactory_p.h>
#include <qmetaobject.h>
#include <qtextlayout.h>
#include <private/qobject_p.h>
#include <private/qdnd_p.h>
#include <private/qtextengine_p.h>
#include <private/qlayoutengine_p.h>
#include <qdebug.h>
#include <qlocale.h>
#include <qdialog.h>
#include <qtableview.h>

#include <limits.h>

QT_BEGIN_NAMESPACE

class QStyledItemDelegatePrivate : public QObjectPrivate
{
    Q_DECLARE_PUBLIC(QStyledItemDelegate)

public:
    QStyledItemDelegatePrivate() : factory(0) { }

    static const QWidget *widget(const QStyleOptionViewItem &option)
    {
        return option.widget;
    }

    const QItemEditorFactory *editorFactory() const
    {
        return factory ? factory : QItemEditorFactory::defaultFactory();
    }

    bool tryFixup(QWidget *editor);
    void _q_commitDataAndCloseEditor(QWidget *editor)
    {
        Q_Q(QStyledItemDelegate);
        emit q->commitData(editor);
        emit q->closeEditor(editor, QAbstractItemDelegate::SubmitModelCache);
    }
    QItemEditorFactory *factory;
};

bool QStyledItemDelegatePrivate::tryFixup(QWidget *editor)
{
#ifndef QT_NO_LINEEDIT
    if (QLineEdit *e = qobject_cast<QLineEdit*>(editor)) {
        if (!e->hasAcceptableInput()) {
            if (const QValidator *validator = e->validator()) {
                QString text = e->text();
                validator->fixup(text);
                e->setText(text);
            }
            return e->hasAcceptableInput();
        }
    }
#endif // QT_NO_LINEEDIT

    return true;
}

/*!
    \class QStyledItemDelegate

    \brief The QStyledItemDelegate class provides display and editing facilities for
    data items from a model.

    \ingroup model-view
    \inmodule QtWidgets

    \since 4.4

    When displaying data from models in Qt item views, e.g., a
    QTableView, the individual items are drawn by a delegate. Also,
    when an item is edited, it provides an editor widget, which is
    placed on top of the item view while editing takes place.
    QStyledItemDelegate is the default delegate for all Qt item
    views, and is installed upon them when they are created.

    The QStyledItemDelegate class is one of the \l{Model/View Classes}
    and is part of Qt's \l{Model/View Programming}{model/view
    framework}. The delegate allows the display and editing of items
    to be developed independently from the model and view.

    The data of items in models are assigned an
    \l{Qt::}{ItemDataRole}; each item can store a QVariant for each
    role. QStyledItemDelegate implements display and editing for the
    most common datatypes expected by users, including booleans,
    integers, and strings.

    The data will be drawn differently depending on which role they
    have in the model. The following table describes the roles and the
    data types the delegate can handle for each of them. It is often
    sufficient to ensure that the model returns appropriate data for
    each of the roles to determine the appearance of items in views.

    \table
    \header \li Role \li Accepted Types
    \omit
    \row    \li \l Qt::AccessibleDescriptionRole \li QString
    \row    \li \l Qt::AccessibleTextRole \li QString
    \endomit
    \row    \li \l Qt::BackgroundRole \li QBrush
    \row    \li \l Qt::BackgroundColorRole \li QColor (obsolete; use Qt::BackgroundRole instead)
    \row    \li \l Qt::CheckStateRole \li Qt::CheckState
    \row    \li \l Qt::DecorationRole \li QIcon, QPixmap, QImage and QColor
    \row    \li \l Qt::DisplayRole \li QString and types with a string representation
    \row    \li \l Qt::EditRole \li See QItemEditorFactory for details
    \row    \li \l Qt::FontRole \li QFont
    \row    \li \l Qt::SizeHintRole \li QSize
    \omit
    \row    \li \l Qt::StatusTipRole \li
    \endomit
    \row    \li \l Qt::TextAlignmentRole \li Qt::Alignment
    \row    \li \l Qt::ForegroundRole \li QBrush
    \row    \li \l Qt::TextColorRole \li QColor (obsolete; use Qt::ForegroundRole instead)
    \omit
    \row    \li \l Qt::ToolTipRole
    \row    \li \l Qt::WhatsThisRole
    \endomit
    \endtable

    Editors are created with a QItemEditorFactory; a default static
    instance provided by QItemEditorFactory is installed on all item
    delegates. You can set a custom factory using
    setItemEditorFactory() or set a new default factory with
    QItemEditorFactory::setDefaultFactory(). It is the data stored in
    the item model with the \l{Qt::}{EditRole} that is edited. See the
    QItemEditorFactory class for a more high-level introduction to
    item editor factories. The \l{Color Editor Factory Example}{Color
    Editor Factory} example shows how to create custom editors with a
    factory.

    \section1 Subclassing QStyledItemDelegate

    If the delegate does not support painting of the data types you
    need or you want to customize the drawing of items, you need to
    subclass QStyledItemDelegate, and reimplement paint() and possibly
    sizeHint(). The paint() function is called individually for each
    item, and with sizeHint(), you can specify the hint for each
    of them.

    When reimplementing paint(), one would typically handle the
    datatypes one would like to draw and use the superclass
    implementation for other types.

    The painting of check box indicators are performed by the current
    style. The style also specifies the size and the bounding
    rectangles in which to draw the data for the different data roles.
    The bounding rectangle of the item itself is also calculated by
    the style. When drawing already supported datatypes, it is
    therefore a good idea to ask the style for these bounding
    rectangles. The QStyle class description describes this in
    more detail.

    If you wish to change any of the bounding rectangles calculated by
    the style or the painting of check box indicators, you can
    subclass QStyle. Note, however, that the size of the items can
    also be affected by reimplementing sizeHint().

    It is possible for a custom delegate to provide editors
    without the use of an editor item factory. In this case, the
    following virtual functions must be reimplemented:

    \list
        \li createEditor() returns the widget used to change data from the model
           and can be reimplemented to customize editing behavior.
        \li setEditorData() provides the widget with data to manipulate.
        \li updateEditorGeometry() ensures that the editor is displayed correctly
           with respect to the item view.
        \li setModelData() returns updated data to the model.
    \endlist

    The \l{Star Delegate Example}{Star Delegate} example creates
    editors by reimplementing these methods.

    \section1 QStyledItemDelegate vs. QItemDelegate

    Since Qt 4.4, there are two delegate classes: QItemDelegate and
    QStyledItemDelegate. However, the default delegate is QStyledItemDelegate.
    These two classes are independent alternatives to painting and providing
    editors for items in views. The difference between them is that
    QStyledItemDelegate uses the current style to paint its items. We therefore
    recommend using QStyledItemDelegate as the base class when implementing
    custom delegates or when working with Qt style sheets. The code required
    for either class should be equal unless the custom delegate needs to use
    the style for drawing.

    If you wish to customize the painting of item views, you should
    implement a custom style. Please see the QStyle class
    documentation for details.

    \sa {Delegate Classes}, QItemDelegate, QAbstractItemDelegate, QStyle,
        {Spin Box Delegate Example}, {Star Delegate Example}, {Color
         Editor Factory Example}
*/


/*!
    Constructs an item delegate with the given \a parent.
*/
QStyledItemDelegate::QStyledItemDelegate(QObject *parent)
    : QAbstractItemDelegate(*new QStyledItemDelegatePrivate(), parent)
{
}

/*!
    Destroys the item delegate.
*/
QStyledItemDelegate::~QStyledItemDelegate()
{
}

/*!
    This function returns the string that the delegate will use to display the
    Qt::DisplayRole of the model in \a locale. \a value is the value of the Qt::DisplayRole
    provided by the model.

    The default implementation uses the QLocale::toString to convert \a value into
    a QString.

    This function is not called for empty model indices, i.e., indices for which
    the model returns an invalid QVariant.

    \sa QAbstractItemModel::data()
*/
QString QStyledItemDelegate::displayText(const QVariant &value, const QLocale& locale) const
{
    QString text;
    switch (value.userType()) {
    case QMetaType::Float:
    case QVariant::Double:
        text = locale.toString(value.toReal());
        break;
    case QVariant::Int:
    case QVariant::LongLong:
        text = locale.toString(value.toLongLong());
        break;
    case QVariant::UInt:
    case QVariant::ULongLong:
        text = locale.toString(value.toULongLong());
        break;
    case QVariant::Date:
        text = locale.toString(value.toDate(), QLocale::ShortFormat);
        break;
    case QVariant::Time:
        text = locale.toString(value.toTime(), QLocale::ShortFormat);
        break;
    case QVariant::DateTime:
        text = locale.toString(value.toDateTime().date(), QLocale::ShortFormat);
        text += QLatin1Char(' ');
        text += locale.toString(value.toDateTime().time(), QLocale::ShortFormat);
        break;
    default:
        // convert new lines into line separators
        text = value.toString();
        for (int i = 0; i < text.count(); ++i) {
            if (text.at(i) == QLatin1Char('\n'))
                text[i] = QChar::LineSeparator;
        }
        break;
    }
    return text;
}

/*!
    Initialize \a option with the values using the index \a index. This method
    is useful for subclasses when they need a QStyleOptionViewItem, but don't want
    to fill in all the information themselves.

    \sa QStyleOption::initFrom()
*/
void QStyledItemDelegate::initStyleOption(QStyleOptionViewItem *option,
                                         const QModelIndex &index) const
{
    QVariant value = index.data(Qt::FontRole);
    if (value.isValid() && !value.isNull()) {
        option->font = qvariant_cast<QFont>(value).resolve(option->font);
        option->fontMetrics = QFontMetrics(option->font);
    }

    value = index.data(Qt::TextAlignmentRole);
    if (value.isValid() && !value.isNull())
        option->displayAlignment = Qt::Alignment(value.toInt());

    value = index.data(Qt::ForegroundRole);
    if (value.canConvert<QBrush>())
        option->palette.setBrush(QPalette::Text, qvariant_cast<QBrush>(value));

    option->index = index;
    value = index.data(Qt::CheckStateRole);
    if (value.isValid() && !value.isNull()) {
        option->features |= QStyleOptionViewItem::HasCheckIndicator;
        option->checkState = static_cast<Qt::CheckState>(value.toInt());
    }

    value = index.data(Qt::DecorationRole);
    if (value.isValid() && !value.isNull()) {
        option->features |= QStyleOptionViewItem::HasDecoration;
        switch (value.type()) {
        case QVariant::Icon: {
            option->icon = qvariant_cast<QIcon>(value);
            QIcon::Mode mode;
            if (!(option->state & QStyle::State_Enabled))
                mode = QIcon::Disabled;
            else if (option->state & QStyle::State_Selected)
                mode = QIcon::Selected;
            else
                mode = QIcon::Normal;
            QIcon::State state = option->state & QStyle::State_Open ? QIcon::On : QIcon::Off;
            QSize actualSize = option->icon.actualSize(option->decorationSize, mode, state);
            // For highdpi icons actualSize might be larger than decorationSize, which we don't want. Clamp it to decorationSize.
            option->decorationSize = QSize(qMin(option->decorationSize.width(), actualSize.width()),
                                           qMin(option->decorationSize.height(), actualSize.height()));
            break;
        }
        case QVariant::Color: {
            QPixmap pixmap(option->decorationSize);
            pixmap.fill(qvariant_cast<QColor>(value));
            option->icon = QIcon(pixmap);
            break;
        }
        case QVariant::Image: {
            QImage image = qvariant_cast<QImage>(value);
            option->icon = QIcon(QPixmap::fromImage(image));
            option->decorationSize = image.size() / image.devicePixelRatio();
            break;
        }
        case QVariant::Pixmap: {
            QPixmap pixmap = qvariant_cast<QPixmap>(value);
            option->icon = QIcon(pixmap);
            option->decorationSize = pixmap.size() / pixmap.devicePixelRatio();
            break;
        }
        default:
            break;
        }
    }

    value = index.data(Qt::DisplayRole);
    if (value.isValid() && !value.isNull()) {
        option->features |= QStyleOptionViewItem::HasDisplay;
        option->text = displayText(value, option->locale);
    }

    option->backgroundBrush = qvariant_cast<QBrush>(index.data(Qt::BackgroundRole));

    // disable style animations for checkboxes etc. within itemviews (QTBUG-30146)
    option->styleObject = 0;
}

/*!
    Renders the delegate using the given \a painter and style \a option for
    the item specified by \a index.

    This function paints the item using the view's QStyle.

    When reimplementing paint in a subclass. Use the initStyleOption()
    to set up the \a option in the same way as the
    QStyledItemDelegate.

    Whenever possible, use the \a option while painting.
    Especially its \l{QStyleOption::}{rect} variable to decide
    where to draw and its \l{QStyleOption::}{state} to determine
    if it is enabled or selected.

    After painting, you should ensure that the painter is returned to
    its the state it was supplied in when this function was called.
    For example, it may be useful to call QPainter::save() before
    painting and QPainter::restore() afterwards.

    \sa QItemDelegate::paint(), QStyle::drawControl(), QStyle::CE_ItemViewItem
*/
void QStyledItemDelegate::paint(QPainter *painter,
        const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_ASSERT(index.isValid());

    QStyleOptionViewItem opt = option;
    initStyleOption(&opt, index);

    const QWidget *widget = QStyledItemDelegatePrivate::widget(option);
    QStyle *style = widget ? widget->style() : QApplication::style();
    style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);
}

/*!
    Returns the size needed by the delegate to display the item
    specified by \a index, taking into account the style information
    provided by \a option.

    This function uses the view's QStyle to determine the size of the
    item.

    \sa QStyle::sizeFromContents(), QStyle::CT_ItemViewItem
*/
QSize QStyledItemDelegate::sizeHint(const QStyleOptionViewItem &option,
                                   const QModelIndex &index) const
{
    QVariant value = index.data(Qt::SizeHintRole);
    if (value.isValid())
        return qvariant_cast<QSize>(value);

    QStyleOptionViewItem opt = option;
    initStyleOption(&opt, index);
    const QWidget *widget = QStyledItemDelegatePrivate::widget(option);
    QStyle *style = widget ? widget->style() : QApplication::style();
    return style->sizeFromContents(QStyle::CT_ItemViewItem, &opt, QSize(), widget);
}

/*!
    Returns the widget used to edit the item specified by \a index
    for editing. The \a parent widget and style \a option are used to
    control how the editor widget appears.

    \sa QAbstractItemDelegate::createEditor()
*/
QWidget *QStyledItemDelegate::createEditor(QWidget *parent,
                                     const QStyleOptionViewItem &,
                                     const QModelIndex &index) const
{
    Q_D(const QStyledItemDelegate);
    if (!index.isValid())
        return 0;
    return d->editorFactory()->createEditor(index.data(Qt::EditRole).userType(), parent);
}

/*!
    Sets the data to be displayed and edited by the \a editor from the
    data model item specified by the model \a index.

    The default implementation stores the data in the \a editor
    widget's \l {Qt's Property System} {user property}.

    \sa QMetaProperty::isUser()
*/
void QStyledItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
#ifdef QT_NO_PROPERTIES
    Q_UNUSED(editor);
    Q_UNUSED(index);
#else
    QVariant v = index.data(Qt::EditRole);
    QByteArray n = editor->metaObject()->userProperty().name();

    if (!n.isEmpty()) {
        if (!v.isValid())
            v = QVariant(editor->property(n).userType(), (const void *)0);
        editor->setProperty(n, v);
    }
#endif
}

/*!
    Gets data from the \a editor widget and stores it in the specified
    \a model at the item \a index.

    The default implementation gets the value to be stored in the data
    model from the \a editor widget's \l {Qt's Property System} {user
    property}.

    \sa QMetaProperty::isUser()
*/
void QStyledItemDelegate::setModelData(QWidget *editor,
                                 QAbstractItemModel *model,
                                 const QModelIndex &index) const
{
#ifdef QT_NO_PROPERTIES
    Q_UNUSED(model);
    Q_UNUSED(editor);
    Q_UNUSED(index);
#else
    Q_D(const QStyledItemDelegate);
    Q_ASSERT(model);
    Q_ASSERT(editor);
    QByteArray n = editor->metaObject()->userProperty().name();
    if (n.isEmpty())
        n = d->editorFactory()->valuePropertyName(
            model->data(index, Qt::EditRole).userType());
    if (!n.isEmpty())
        model->setData(index, editor->property(n), Qt::EditRole);
#endif
}

/*!
    Updates the \a editor for the item specified by \a index
    according to the style \a option given.
*/
void QStyledItemDelegate::updateEditorGeometry(QWidget *editor,
                                         const QStyleOptionViewItem &option,
                                         const QModelIndex &index) const
{
    if (!editor)
        return;
    Q_ASSERT(index.isValid());
    const QWidget *widget = QStyledItemDelegatePrivate::widget(option);

    QStyleOptionViewItem opt = option;
    initStyleOption(&opt, index);
    // let the editor take up all available space
    //if the editor is not a QLineEdit
    //or it is in a QTableView
#if !defined(QT_NO_TABLEVIEW) && !defined(QT_NO_LINEEDIT)
    if (qobject_cast<QExpandingLineEdit*>(editor) && !qobject_cast<const QTableView*>(widget))
        opt.showDecorationSelected = editor->style()->styleHint(QStyle::SH_ItemView_ShowDecorationSelected, 0, editor);
    else
#endif
        opt.showDecorationSelected = true;

    QStyle *style = widget ? widget->style() : QApplication::style();
    QRect geom = style->subElementRect(QStyle::SE_ItemViewItemText, &opt, widget);
    if ( editor->layoutDirection() == Qt::RightToLeft) {
        const int delta = qSmartMinSize(editor).width() - geom.width();
        if (delta > 0) {
            //we need to widen the geometry
            geom.adjust(-delta, 0, 0, 0);
        }
    }

    editor->setGeometry(geom);
}

/*!
  Returns the editor factory used by the item delegate.
  If no editor factory is set, the function will return null.

  \sa setItemEditorFactory()
*/
QItemEditorFactory *QStyledItemDelegate::itemEditorFactory() const
{
    Q_D(const QStyledItemDelegate);
    return d->factory;
}

/*!
  Sets the editor factory to be used by the item delegate to be the \a factory
  specified. If no editor factory is set, the item delegate will use the
  default editor factory.

  \sa itemEditorFactory()
*/
void QStyledItemDelegate::setItemEditorFactory(QItemEditorFactory *factory)
{
    Q_D(QStyledItemDelegate);
    d->factory = factory;
}


/*!
    \fn bool QStyledItemDelegate::eventFilter(QObject *editor, QEvent *event)

    Returns \c true if the given \a editor is a valid QWidget and the
    given \a event is handled; otherwise returns \c false. The following
    key press events are handled by default:

    \list
        \li \uicontrol Tab
        \li \uicontrol Backtab
        \li \uicontrol Enter
        \li \uicontrol Return
        \li \uicontrol Esc
    \endlist

    If the \a editor's type is QTextEdit or QPlainTextEdit then \uicontrol Enter and
    \uicontrol Return keys are \e not handled.

    In the case of \uicontrol Tab, \uicontrol Backtab, \uicontrol Enter and \uicontrol Return
    key press events, the \a editor's data is comitted to the model
    and the editor is closed. If the \a event is a \uicontrol Tab key press
    the view will open an editor on the next item in the
    view. Likewise, if the \a event is a \uicontrol Backtab key press the
    view will open an editor on the \e previous item in the view.

    If the event is a \uicontrol Esc key press event, the \a editor is
    closed \e without committing its data.

    \sa commitData(), closeEditor()
*/
bool QStyledItemDelegate::eventFilter(QObject *object, QEvent *event)
{
    Q_D(QStyledItemDelegate);

    QWidget *editor = qobject_cast<QWidget*>(object);
    if (!editor)
        return false;
    if (event->type() == QEvent::KeyPress) {
        switch (static_cast<QKeyEvent *>(event)->key()) {
        case Qt::Key_Tab:
            if (d->tryFixup(editor)) {
                emit commitData(editor);
                emit closeEditor(editor, EditNextItem);
            }
            return true;
        case Qt::Key_Backtab:
            if (d->tryFixup(editor)) {
                emit commitData(editor);
                emit closeEditor(editor, EditPreviousItem);
            }
            return true;
        case Qt::Key_Enter:
        case Qt::Key_Return:
#ifndef QT_NO_TEXTEDIT
            if (qobject_cast<QTextEdit *>(editor) || qobject_cast<QPlainTextEdit *>(editor))
                return false; // don't filter enter key events for QTextEdit
            // We want the editor to be able to process the key press
            // before committing the data (e.g. so it can do
            // validation/fixup of the input).
#endif // QT_NO_TEXTEDIT
            if (!d->tryFixup(editor))
                return true;

            QMetaObject::invokeMethod(this, "_q_commitDataAndCloseEditor",
                                      Qt::QueuedConnection, Q_ARG(QWidget*, editor));
            return false;
        case Qt::Key_Escape:
            // don't commit data
            emit closeEditor(editor, QAbstractItemDelegate::RevertModelCache);
            return true;
        default:
            return false;
        }
    } else if (event->type() == QEvent::FocusOut || (event->type() == QEvent::Hide && editor->isWindow())) {
        //the Hide event will take care of he editors that are in fact complete dialogs
        if (!editor->isActiveWindow() || (QApplication::focusWidget() != editor)) {
            QWidget *w = QApplication::focusWidget();
            while (w) { // don't worry about focus changes internally in the editor
                if (w == editor)
                    return false;
                w = w->parentWidget();
            }
#ifndef QT_NO_DRAGANDDROP
            // The window may lose focus during an drag operation.
            // i.e when dragging involves the taskbar on Windows.
            QPlatformDrag *platformDrag = QGuiApplicationPrivate::instance()->platformIntegration()->drag();
            if (platformDrag && platformDrag->currentDrag()) {
                return false;
            }
#endif
            if (d->tryFixup(editor))
                emit commitData(editor);

            emit closeEditor(editor, NoHint);
        }
    } else if (event->type() == QEvent::ShortcutOverride) {
        if (static_cast<QKeyEvent*>(event)->key() == Qt::Key_Escape) {
            event->accept();
            return true;
        }
    }
    return false;
}

/*!
  \reimp
*/
bool QStyledItemDelegate::editorEvent(QEvent *event,
                                QAbstractItemModel *model,
                                const QStyleOptionViewItem &option,
                                const QModelIndex &index)
{
    Q_ASSERT(event);
    Q_ASSERT(model);

    // make sure that the item is checkable
    Qt::ItemFlags flags = model->flags(index);
    if (!(flags & Qt::ItemIsUserCheckable) || !(option.state & QStyle::State_Enabled)
        || !(flags & Qt::ItemIsEnabled))
        return false;

    // make sure that we have a check state
    QVariant value = index.data(Qt::CheckStateRole);
    if (!value.isValid())
        return false;

    const QWidget *widget = QStyledItemDelegatePrivate::widget(option);
    QStyle *style = widget ? widget->style() : QApplication::style();

    // make sure that we have the right event type
    if ((event->type() == QEvent::MouseButtonRelease)
        || (event->type() == QEvent::MouseButtonDblClick)
        || (event->type() == QEvent::MouseButtonPress)) {
        QStyleOptionViewItem viewOpt(option);
        initStyleOption(&viewOpt, index);
        QRect checkRect = style->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, widget);
        QMouseEvent *me = static_cast<QMouseEvent*>(event);
        if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos()))
            return false;

        if ((event->type() == QEvent::MouseButtonPress)
            || (event->type() == QEvent::MouseButtonDblClick))
            return true;

    } else if (event->type() == QEvent::KeyPress) {
        if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Space
         && static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select)
            return false;
    } else {
        return false;
    }

    Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
    if (flags & Qt::ItemIsTristate)
        state = ((Qt::CheckState)((state + 1) % 3));
    else
        state = (state == Qt::Checked) ? Qt::Unchecked : Qt::Checked;
    return model->setData(index, state, Qt::CheckStateRole);
}

QT_END_NAMESPACE

#include "moc_qstyleditemdelegate.cpp"

#endif // QT_NO_ITEMVIEWS