qitemdelegate.cpp

来自「QT 开发环境里面一个很重要的文件」· C++ 代码 · 共 1,145 行 · 第 1/3 页

CPP
1,145
字号
    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.    When reimplementing this function, note that in case of text    items, QItemDelegate adds a margin (i.e. 2 *    QStyle::PM_FocusFrameHMargin) to the length of the text.*/QSize QItemDelegate::sizeHint(const QStyleOptionViewItem &option,                              const QModelIndex &index) const{    QVariant value = index.data(Qt::SizeHintRole);    if (value.isValid())        return qvariant_cast<QSize>(value);    QRect decorationRect = rect(option, index, Qt::DecorationRole);    QRect displayRect = rect(option, index, Qt::DisplayRole);    QRect checkRect = rect(option, index, Qt::CheckStateRole);    doLayout(option, &checkRect, &decorationRect, &displayRect, true);    return (decorationRect|displayRect|checkRect).size();}/*!    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 *QItemDelegate::createEditor(QWidget *parent,                                     const QStyleOptionViewItem &,                                     const QModelIndex &index) const{    Q_D(const QItemDelegate);    if (!index.isValid())        return 0;    QVariant::Type t = static_cast<QVariant::Type>(index.data(Qt::EditRole).userType());    const QItemEditorFactory *factory = d->f;    if (factory == 0)        factory = QItemEditorFactory::defaultFactory();    return factory->createEditor(t, parent);}/*!    Sets the data to be displayed and edited by the \a editor for the    item specified by \a index.    The default implementation uses the editor's user property to set values.    \sa QMetaProperty::isUser()*/void QItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const{#ifdef QT_NO_PROPERTIES    Q_UNUSED(editor);    Q_UNUSED(index);#else    Q_D(const QItemDelegate);    QVariant v = index.data(Qt::EditRole);    QByteArray n = editor->metaObject()->userProperty().name();    // ### Remove in Qt 5: A work-around for missing "USER true" in    // qdatetimeedit.h for QTimeEdit's time property and QDateEdit's date    // property. It only triggers if the default user property "dateTime" is    // reported for QTimeEdit and QDateEdit.    if (n == "dateTime") {        if (editor->inherits("QTimeEdit"))            n = "time";        else if (editor->inherits("QDateEdit"))            n = "date";    }    if (n.isEmpty())        n = d->editorFactory()->valuePropertyName(static_cast<QVariant::Type>(v.userType()));    if (!n.isEmpty())        editor->setProperty(n, v);#endif}/*!    Sets the data for the specified \a model and item \a index from that    supplied by the \a editor.    The default implementation uses the editor's user property to get values.    \sa QMetaProperty::isUser()*/void QItemDelegate::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 QItemDelegate);    Q_ASSERT(model);    Q_ASSERT(editor);    QByteArray n = editor->metaObject()->userProperty().name();    if (n.isEmpty())        n = d->editorFactory()->valuePropertyName(            static_cast<QVariant::Type>(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 QItemDelegate::updateEditorGeometry(QWidget *editor,                                         const QStyleOptionViewItem &option,                                         const QModelIndex &index) const{    if (!editor)        return;    Q_ASSERT(index.isValid());    QPixmap pixmap = decoration(option, index.data(Qt::DecorationRole));    QString text = QItemDelegatePrivate::replaceNewLine(index.data(Qt::DisplayRole).toString());    QRect pixmapRect = QRect(QPoint(0, 0), option.decorationSize).intersected(pixmap.rect());    QRect textRect = textRectangle(0, option.rect, option.font, text);    QRect checkRect = check(option, textRect, index.data(Qt::CheckStateRole));    QStyleOptionViewItem opt = option;    opt.showDecorationSelected = true; // let the editor take up all available space    doLayout(opt, &checkRect, &pixmapRect, &textRect, false);    editor->setGeometry(textRect);}/*!  Returns the editor factory used by the item delegate.  If no editor factory is set, the function will return null.  \sa setItemEditorFactory()*/QItemEditorFactory *QItemDelegate::itemEditorFactory() const{    Q_D(const QItemDelegate);    return d->f;}/*!  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 QItemDelegate::setItemEditorFactory(QItemEditorFactory *factory){    Q_D(QItemDelegate);    d->f = factory;}/*!   Renders the item view \a text within the rectangle specified by \a rect   using the given \a painter and style \a option.*/void QItemDelegate::drawDisplay(QPainter *painter, const QStyleOptionViewItem &option,                                const QRect &rect, const QString &text) const{    Q_D(const QItemDelegate);    if (text.isEmpty())        return;    QPen pen = painter->pen();    QPalette::ColorGroup cg = option.state & QStyle::State_Enabled                              ? QPalette::Normal : QPalette::Disabled;    if (cg == QPalette::Normal && !(option.state & QStyle::State_Active))        cg = QPalette::Inactive;    if (option.state & QStyle::State_Selected) {        painter->fillRect(rect, option.palette.brush(cg, QPalette::Highlight));        painter->setPen(option.palette.color(cg, QPalette::HighlightedText));    } else {        painter->setPen(option.palette.color(cg, QPalette::Text));    }    if (option.state & QStyle::State_Editing) {        painter->save();        painter->setPen(option.palette.color(cg, QPalette::Text));        painter->drawRect(rect.adjusted(0, 0, -1, -1));        painter->restore();    }    const QStyleOptionViewItemV2 opt = option;    const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;    QRect textRect = rect.adjusted(textMargin, 0, -textMargin, 0); // remove width padding    const bool wrapText = opt.features & QStyleOptionViewItemV2::WrapText;    d->textOption.setWrapMode(wrapText ? QTextOption::WordWrap : QTextOption::ManualWrap);    d->textOption.setTextDirection(option.direction);    d->textOption.setAlignment(QStyle::visualAlignment(option.direction, option.displayAlignment));    d->textLayout.setTextOption(d->textOption);    d->textLayout.setFont(option.font);    d->textLayout.setText(QItemDelegatePrivate::replaceNewLine(text));    QSizeF textLayoutSize = d->doTextLayout(textRect.width());    if (textRect.width() < textLayoutSize.width()        || textRect.height() < textLayoutSize.height()) {        QString elided;        int start = 0;        int end = text.indexOf(QChar::LineSeparator, start);        if (end == -1) {            elided += option.fontMetrics.elidedText(text, option.textElideMode, textRect.width());        } else while (end != -1) {            elided += option.fontMetrics.elidedText(text.mid(start, end - start),                                                    option.textElideMode, textRect.width());            start = end + 1;            end = text.indexOf(QChar::LineSeparator, start);        }        d->textLayout.setText(elided);        textLayoutSize = d->doTextLayout(textRect.width());    }    const QSize layoutSize(textRect.width(), int(textLayoutSize.height()));    const QRect layoutRect = QStyle::alignedRect(option.direction, option.displayAlignment,                                                  layoutSize, textRect);    d->textLayout.draw(painter, layoutRect.topLeft(), QVector<QTextLayout::FormatRange>(), layoutRect);}/*!    Renders the decoration \a pixmap within the rectangle specified by    \a rect using the given \a painter and style \a option.*/void QItemDelegate::drawDecoration(QPainter *painter, const QStyleOptionViewItem &option,                                   const QRect &rect, const QPixmap &pixmap) const{    if (pixmap.isNull() || !rect.isValid())        return;    QPoint p = QStyle::alignedRect(option.direction, option.decorationAlignment,                                   pixmap.size(), rect).topLeft();    if (option.state & QStyle::State_Selected) {        QPixmap *pm = selected(pixmap, option.palette, option.state & QStyle::State_Enabled);        painter->drawPixmap(p, *pm);    } else {        painter->drawPixmap(p, pixmap);    }}/*!    Renders the region within the rectangle specified by \a rect, indicating    that it has the focus, using the given \a painter and style \a option.*/void QItemDelegate::drawFocus(QPainter *painter,                              const QStyleOptionViewItem &option,                              const QRect &rect) const{    if ((option.state & QStyle::State_HasFocus) == 0 || !rect.isValid())        return;    QStyleOptionFocusRect o;    o.QStyleOption::operator=(option);    o.rect = rect;    o.state |= QStyle::State_KeyboardFocusChange;    QPalette::ColorGroup cg = (option.state & QStyle::State_Enabled)                              ? QPalette::Normal : QPalette::Disabled;    o.backgroundColor = option.palette.color(cg, (option.state & QStyle::State_Selected)                                             ? QPalette::Highlight : QPalette::Window);    QApplication::style()->drawPrimitive(QStyle::PE_FrameFocusRect, &o, painter);}/*!    Renders a check indicator within the rectangle specified by \a    rect, using the given \a painter and style \a option, using the    given \a state.*/void QItemDelegate::drawCheck(QPainter *painter,                              const QStyleOptionViewItem &option,                              const QRect &rect, Qt::CheckState state) const{    if (!rect.isValid())        return;    QStyleOptionViewItem opt(option);    opt.rect = rect;    opt.state = opt.state & ~QStyle::State_HasFocus;    switch (state) {    case Qt::Unchecked:        opt.state |= QStyle::State_Off;        break;    case Qt::PartiallyChecked:        opt.state |= QStyle::State_NoChange;        break;    case Qt::Checked:        opt.state |= QStyle::State_On;        break;    }    QApplication::style()->drawPrimitive(QStyle::PE_IndicatorViewItemCheck, &opt, painter);}/*!    \since 4.2    Renders the item background for the given \a index,    using the given \a painter and style \a option.*/void QItemDelegate::drawBackground(QPainter *painter,                                   const QStyleOptionViewItem &option,                                   const QModelIndex &index) const{    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 {        QVariant value = index.data(Qt::BackgroundRole);        if (qVariantCanConvert<QBrush>(value)) {            QPointF oldBO = painter->brushOrigin();            painter->setBrushOrigin(option.rect.topLeft());            painter->fillRect(option.rect, qvariant_cast<QBrush>(value));            painter->setBrushOrigin(oldBO);        }    }}/*!    \internal*/void QItemDelegate::doLayout(const QStyleOptionViewItem &option,                             QRect *checkRect, QRect *pixmapRect, QRect *textRect,                             bool hint) const{    Q_ASSERT(checkRect && pixmapRect && textRect);    const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;    int x = option.rect.left();    int y = option.rect.top();    int w, h;    textRect->adjust(-textMargin, 0, textMargin, 0); // add width padding    if (textRect->height() == 0)        textRect->setHeight(option.fontMetrics.lineSpacing());    QSize pm(0, 0);    if (pixmapRect->isValid()) {        pm = pixmapRect->size();        pm.rwidth() += 2 * textMargin;    }    if (hint) {        h = qMax(checkRect->height(), qMax(textRect->height(), pm.height()));        if (option.decorationPosition == QStyleOptionViewItem::Left            || option.decorationPosition == QStyleOptionViewItem::Right) {            w = textRect->width() + pm.width();        } else {            w = qMax(textRect->width(), pm.width());        }    } else {        w = option.rect.width();        h = option.rect.height();    }    int cw = 0;    QRect check;    if (checkRect->isValid()) {        cw = checkRect->width() + 2 * textMargin;        if (hint) w += cw;        if (option.direction == Qt::RightToLeft) {            check.setRect(x + w - cw, y, cw, h);        } else {            check.setRect(x, y, cw, h);        }    }    // at this point w should be the *total* width

⌨️ 快捷键说明

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