⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 qitemdelegate.cpp

📁 qt-x11-opensource-src-4.1.4.tar.gz源码
💻 CPP
📖 第 1 页 / 共 3 页
字号:
/******************************************************************************** Copyright (C) 1992-2006 Trolltech ASA. All rights reserved.**** This file is part of the QtGui module of the Qt Toolkit.**** This file may be used under the terms of the GNU General Public** License version 2.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 GNU** General Public Licensing requirements will be met:** http://www.trolltech.com/products/qt/opensource.html**** If you are unsure which license is appropriate for your use, please** review the following information:** http://www.trolltech.com/products/qt/licensing.html or contact the** sales department at sales@trolltech.com.**** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.******************************************************************************/#include "qitemdelegate.h"#ifndef QT_NO_ITEMVIEWS#include <qabstractitemmodel.h>#include <qapplication.h>#include <qlineedit.h>#include <qpainter.h>#include <qpalette.h>#include <qpoint.h>#include <qrect.h>#include <qsize.h>#include <qstyle.h>#include <qstyleoption.h>#include <qevent.h>#include <qpixmap.h>#include <qbitmap.h>#include <qpixmapcache.h>#include <qitemeditorfactory.h>#include <private/qobject_p.h>#include <private/qdnd_p.h>#include <qdebug.h>void qt_format_text(const QFont&, const QRectF&,                    int, const QString&, QRectF *,                    int, int*, int, QPainter*);static const int textMargin = 3;class QItemDelegatePrivate : public QObjectPrivate{    Q_DECLARE_PUBLIC(QItemDelegate)public:    QItemDelegatePrivate() : f(0) {}    inline const QItemEditorFactory *editorFactory() const        { return f ? f : QItemEditorFactory::defaultFactory(); }    QItemEditorFactory *f;};/*!    \class QItemDelegate    \brief The QItemDelegate class provides display and editing facilities for    data items from a model.    \ingroup model-view    \mainclass    QItemDelegate can be used to provide custom display features and editor    widgets for item views based on QAbstractItemView subclasses. Using a    delegate for this purpose allows the display and editing mechanisms to be    customized and developed independently from the model and view.    The QItemDelegate class is one of the \l{Model/View Classes}    and is part of Qt's \l{Model/View Programming}{model/view framework}.    When displaying items from a custom model in a standard view, it is    often sufficient to simply ensure that the model returns appropriate    data for each of the \l{Qt::ItemDataRole}{roles} that determine the    appearance of items in views. The default delegate used by Qt's    standard views uses this role information to display items in most    of the common forms expected by users. However, it is sometimes    necessary to have even more control over the appearance of items than    the default delegate can provide.    This class provides default implementations of the functions for    painting item data in a view, and editing data obtained from a model.    Default implementations of the paint() and sizeHint() virtual functions,    defined in QAbstractItemDelegate, are provided to ensure that the    delegate implements the correct basic behavior expected by views. You    can reimplement these functions in subclasses to customize the    appearance of items.    Delegates can be used to manipulate item data in two complementary ways:    by processing events in the normal manner, or by implementing a    custom editor widget. The item delegate takes the approach of providing    a widget for editing purposes that can be supplied to    QAbstractItemView::setDelegate() or the equivalent function in    subclasses of QAbstractItemView.    Only the standard editing functions for widget-based delegates are    reimplemented here: editor() returns the widget used to change data    from the model; setEditorData() provides the widget with data to    manipulate; updateEditorGeometry() ensures that the editor is displayed    correctly with respect to the item view; setModelData() returns the    updated data to the model; releaseEditor() indicates that the user has    completed editing the data, and that the editor widget can be destroyed.    \section1 Standard Roles and Data Types    The default delegate used by the standard views supplied with Qt    associates each standard role (defined by Qt::ItemDataRole) with certain    data types. Models that return data in these types can influence the    appearance of the delegate as described in the following table.    \table    \header \o Role \o Accepted Types    \omit    \row    \o \l Qt::AccessibleDescriptionRole \o QString    \row    \o \l Qt::AccessibleTextRole \o QString    \endomit    \row    \o \l Qt::BackgroundColorRole \o QColor    \row    \o \l Qt::CheckStateRole \o Qt::CheckState    \row    \o \l Qt::DecorationRole \o QIcon and QColor    \row    \o \l Qt::DisplayRole \o QString and types with a string representation    \row    \o \l Qt::EditRole \o See QItemEditorFactory for details    \row    \o \l Qt::FontRole \o QFont    \row    \o \l Qt::SizeHintRole \o QSize    \omit    \row    \o \l Qt::StatusTipRole \o     \endomit    \row    \o \l Qt::TextAlignmentRole \o Qt::Alignment    \row    \o \l Qt::TextColorRole \o QColor    \omit    \row    \o \l Qt::ToolTipRole    \row    \o \l Qt::WhatsThisRole    \endomit    \endtable    If the default delegate does not allow the level of customization that    you need, it is possible to subclass QItemDelegate to implement the    desired behavior.    \section1 Subclassing    When subclassing QItemDelegate to create a delegate that displays items    using a custom renderer, it is important to ensure that the delegate can    render items suitably for all the required states; e.g. selected,    disabled, checked. The documentation for the paint() function contains    some hints to show how this can be achieved.    \sa {Model/View Programming}, QAbstractItemDelegate*//*!    Constructs an item delegate with the given \a parent.*/QItemDelegate::QItemDelegate(QObject *parent)    : QAbstractItemDelegate(*new QItemDelegatePrivate(), parent){}/*!    Destroys the item delegate.*/QItemDelegate::~QItemDelegate(){}/*!    Renders the delegate using the given \a painter and style \a option for    the item specified by \a index.    When reimplementing this function in a subclass, you should update the area    held by the option's \l{QStyleOption::rect}{rect} variable, using the    option's \l{QStyleOption::state}{state} variable to determine the state of    the item to be displayed, and adjust the way it is painted accordingly.    For example, a selected item may need to be displayed differently to    unselected items, as shown in the following code:    \quotefromfile itemviews/pixelator/pixeldelegate.cpp    \skipto QStyle::State_Selected    \printuntil else    \dots    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 QStyle::State*/void QItemDelegate::paint(QPainter *painter,                          const QStyleOptionViewItem &option,                          const QModelIndex &index) const{    Q_ASSERT(index.isValid());    QStyleOptionViewItem opt = option;    // set font    QVariant value = index.data(Qt::FontRole);    if (value.isValid()) {        opt.font = qvariant_cast<QFont>(value);        opt.fontMetrics = QFontMetrics(opt.font);    }    // set text alignment    value = index.data(Qt::TextAlignmentRole);    if (value.isValid())        opt.displayAlignment = QFlag(value.toInt());    // set text color    value = index.data(Qt::TextColorRole);    if (value.isValid() && qvariant_cast<QColor>(value).isValid())        opt.palette.setColor(QPalette::Text, qvariant_cast<QColor>(value));    // do layout    // decoration    value = index.data(Qt::DecorationRole);    QPixmap pixmap = decoration(opt, value);    QRect pixmapRect = (pixmap.isNull() ? QRect(0, 0, 0, 0)                        : QRect(QPoint(0, 0), option.decorationSize));    // display    QRect textRect;    QString text = index.data(Qt::DisplayRole).toString();    if (!text.isEmpty()) {        const QString text = index.data(Qt::DisplayRole).toString();        const QChar *chr = text.constData();        const QChar *end = chr + text.length();        while (chr != end               && *chr != QLatin1Char('\n')               && *chr != QLatin1Char('\t')               && *chr != QLatin1Char('&')) ++chr;        if (chr == end) {            textRect = QRect(0, 0, opt.fontMetrics.width(text), opt.fontMetrics.lineSpacing());        } else {            QRectF result;            qt_format_text(opt.font, option.rect,                           Qt::TextDontPrint|Qt::TextDontClip|Qt::TextExpandTabs,                       text, &result, 0, 0, 0, painter);            textRect = result.toRect();        }    }    // check    value = index.data(Qt::CheckStateRole);    QRect checkRect = check(opt, opt.rect, value);    Qt::CheckState checkState = static_cast<Qt::CheckState>(value.toInt());    doLayout(opt, &checkRect, &pixmapRect, &textRect, false);    // draw the background color    if (option.showDecorationSelected && (option.state & QStyle::State_Selected)) {        QPalette::ColorGroup cg = option.state & QStyle::State_Enabled                                  ? QPalette::Normal : QPalette::Disabled;        if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))            cg = QPalette::Inactive;        painter->fillRect(option.rect, option.palette.brush(cg, QPalette::Highlight));    } else {        value = index.data(Qt::BackgroundColorRole);        if (value.isValid() && qvariant_cast<QColor>(value).isValid())            painter->fillRect(option.rect, qvariant_cast<QColor>(value));    }    // draw the item    if (checkRect.isValid())        drawCheck(painter, opt, checkRect, checkState);    if (pixmapRect.isValid())        drawDecoration(painter, opt, pixmapRect, pixmap);    if (!text.isEmpty()) {        drawDisplay(painter, opt, textRect, text);        drawFocus(painter, opt, textRect);    }}/*!    Returns the size needed by the delegate to display the item    specified by \a index, taking into account the style information

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -