qtreeview.cpp

来自「奇趣公司比较新的qt/emd版本」· C++ 代码 · 共 2,004 行 · 第 1/5 页

CPP
2,004
字号
    \brief whether sorting is enabled    If this property is true, sorting is enabled for the tree; if the property    is false, sorting is not enabled. The default value is false.    \sa sortByColumn()*/void QTreeView::setSortingEnabled(bool enable){    Q_D(QTreeView);    d->sortingEnabled = enable;    header()->setSortIndicatorShown(enable);    header()->setClickable(enable);    if (enable) {        connect(header(), SIGNAL(sectionClicked(int)), this, SLOT(sortByColumn(int)));        sortByColumn(header()->sortIndicatorSection());    } else {        disconnect(header(), SIGNAL(sectionClicked(int)), this, SLOT(sortByColumn(int)));    }}bool QTreeView::isSortingEnabled() const{    Q_D(const QTreeView);    return d->sortingEnabled;}/*!    \since Qt 4.2    \property QTreeView::animated    \brief whether animations are enabled    If this property is true the treeview will animate expandsion    and collasping of branches. If this property is false, the treeview    will expand or collapse branches immediately without showing    the animation.*/void QTreeView::setAnimated(bool animate){    Q_D(QTreeView);    d->animationsEnabled = animate;}bool QTreeView::isAnimated() const{    Q_D(const QTreeView);    return d->animationsEnabled;}/*!    \since 4.2    \property QTreeView::allColumnsShowFocus    \brief whether items should show keyboard focus using all columns    If this property is true all columns will show focus, otherwise only    one column will show focus.    The default is false.*/void QTreeView::setAllColumnsShowFocus(bool enable){    Q_D(QTreeView);    if (d->allColumnsShowFocus == enable)        return;    if (d->selectionModel) {        if (enable) {            QObject::connect(d->selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)),                             this, SLOT(_q_currentChanged(QModelIndex,QModelIndex)));        } else {            QObject::disconnect(d->selectionModel, SIGNAL(currentChanged(QModelIndex,QModelIndex)),                                this, SLOT(_q_currentChanged(QModelIndex,QModelIndex)));        }    }    d->allColumnsShowFocus = enable;    d->viewport->update();}bool QTreeView::allColumnsShowFocus() const{    Q_D(const QTreeView);    return d->allColumnsShowFocus;}/*!    \property QTreeView::wordWrap    \brief the item text word-wrapping policy    \since 4.3    If this property is true then the item text is wrapped where    necessary at word-breaks; otherwise it is not wrapped at all.    This property is false by default.*/void QTreeView::setWordWrap(bool on){    Q_D(QTreeView);    if (d->wrapItemText == on)        return;    d->wrapItemText = on;    d->doDelayedItemsLayout();}bool QTreeView::wordWrap() const{    Q_D(const QTreeView);    return d->wrapItemText;}/*!  \reimp */void QTreeView::keyboardSearch(const QString &search){    Q_D(QTreeView);    if (!d->model->rowCount(d->root) || !d->model->columnCount(d->root))        return;    QModelIndex start;    if (currentIndex().isValid())        start = currentIndex();    else        start = d->model->index(0, 0, d->root);    QTime now(QTime::currentTime());    bool skipRow = false;    if (search.isEmpty()        || (d->keyboardInputTime.msecsTo(now) > QApplication::keyboardInputInterval())) {        d->keyboardInput = search;        skipRow = true;    } else {        d->keyboardInput += search;    }    d->keyboardInputTime = now;    // special case for searches with same key like 'aaaaa'    bool sameKey = false;    if (d->keyboardInput.length() > 1) {        int c = d->keyboardInput.count(d->keyboardInput.at(d->keyboardInput.length() - 1));        sameKey = (c == d->keyboardInput.length());        if (sameKey)            skipRow = true;    }    // skip if we are searching for the same key or a new search started    if (skipRow) {        if (indexBelow(start).isValid())            start = indexBelow(start);        else            start = d->model->index(0, start.column(), d->root);    }    d->executePostedLayout();    int startIndex = d->viewIndex(start);    if (startIndex <= -1)        return;    int previousLevel = -1;    int bestAbove = -1;    int bestBelow = -1;    QString searchString = sameKey ? QString(d->keyboardInput.at(0)) : d->keyboardInput;    for (int i = 0; i < d->viewItems.count(); ++i) {        if ((int)d->viewItems.at(i).level > previousLevel) {            QModelIndex searchFrom = d->viewItems.at(i).index;            if (searchFrom.parent() == start.parent())                searchFrom = start;            QModelIndexList match = d->model->match(searchFrom, Qt::DisplayRole, searchString);            if (match.count()) {                int hitIndex = d->viewIndex(match.at(0));                if (hitIndex >= 0 && hitIndex < startIndex)                    bestAbove = bestAbove == -1 ? hitIndex : qMin(hitIndex, bestAbove);                else if (hitIndex >= startIndex)                    bestBelow = bestBelow == -1 ? hitIndex : qMin(hitIndex, bestBelow);            }        }        previousLevel = d->viewItems.at(i).level;    }    QModelIndex index;    if (bestBelow > -1)        index = d->viewItems.at(bestBelow).index;    else if (bestAbove > -1)        index = d->viewItems.at(bestAbove).index;    if (index.isValid()) {        QItemSelectionModel::SelectionFlags flags = (d->selectionMode == SingleSelection                                                     ? QItemSelectionModel::SelectionFlags(                                                         QItemSelectionModel::ClearAndSelect                                                         |d->selectionBehaviorFlags())                                                     : QItemSelectionModel::SelectionFlags(                                                         QItemSelectionModel::NoUpdate));        selectionModel()->setCurrentIndex(index, flags);    }}/*!  Returns the rectangle on the viewport occupied by the item at \a index.  If the index is not visible or explicitly hidden, the returned rectangle is invalid.*/QRect QTreeView::visualRect(const QModelIndex &index) const{    Q_D(const QTreeView);    if (!d->isIndexValid(index) || isIndexHidden(index))        return QRect();    d->executePostedLayout();    int vi = d->viewIndex(index);    if (vi < 0)        return QRect();    bool spanning = d->viewItems.at(vi).spanning;    bool firstColumnMoved = (d->header && d->header->logicalIndex(0) != 0);    // if we have a spanning item, make the selection stretch from left to right    int x = (spanning ? 0 : columnViewportPosition(index.column()));    int w = (spanning ? d->header->length() : columnWidth(index.column()));    // handle indentation    if (index.column() == 0 && !firstColumnMoved && !spanning) {        int i = d->indentationForItem(vi);        x += i;        w -= i;    }    int y = d->coordinateForItem(vi);    int h = d->itemHeight(vi);    return QRect(x, y, w, h);}/*!    Scroll the contents of the tree view until the given model item    \a index is visible. The \a hint parameter specifies more    precisely where the item should be located after the    operation.    If any of the parents of the model item are collapsed, they will    be expanded to ensure that the model item is visible.*/void QTreeView::scrollTo(const QModelIndex &index, ScrollHint hint){    Q_D(QTreeView);    if (!d->isIndexValid(index))        return;    d->executePostedLayout();    d->updateScrollBars();    // Expand all parents if the parent(s) of the node are not expanded.    QModelIndex parent = index.parent();    while (parent.isValid() && state() == NoState && d->itemsExpandable) {        if (!isExpanded(parent))            expand(parent);        parent = d->model->parent(parent);    }    int item = d->viewIndex(index);    if (item < 0)        return;    QRect area = d->viewport->rect();    // vertical    if (verticalScrollMode() == QAbstractItemView::ScrollPerItem) {        int top = verticalScrollBar()->value();        int bottom = top + verticalScrollBar()->pageStep();        if (hint == EnsureVisible && item >= top && item < bottom) {            return; // nothing to do        } else if (hint == PositionAtTop || item < top) {            verticalScrollBar()->setValue(item);        } else { // PositionAtBottom or PositionAtCenter            int y = (hint == PositionAtCenter                     ? area.height() / 2                     : area.height());            while (y > 0 && item > 0)                y -= d->itemHeight(item--);            item += 1 + ((y < 0) ? 1 : 0);            verticalScrollBar()->setValue(item);        }    } else { // ScrollPerPixel        QRect rect(columnViewportPosition(index.column()),                   d->coordinateForItem(item), // ### slow for items outside the view                   columnWidth(index.column()),                   d->itemHeight(item));        if (rect.isEmpty())            return;        if (hint == EnsureVisible && area.contains(rect)) {            d->setDirtyRegion(rect);            return; // nothing to do        }        bool above = (hint == EnsureVisible                      && (rect.top() < area.top()                          || area.height() < rect.height()));        bool below = (hint == EnsureVisible                      && rect.bottom() > area.bottom()                      && rect.height() < area.height());        int verticalValue = verticalScrollBar()->value();        if (hint == PositionAtTop || above)            verticalValue += rect.top();        else if (hint == PositionAtBottom || below)            verticalValue += rect.bottom() - area.height();        else if (hint == PositionAtCenter)            verticalValue += rect.top() - ((area.height() - rect.height()) / 2);        verticalScrollBar()->setValue(verticalValue);    }    // horizontal    int viewportWidth = d->viewport->width();    int horizontalOffset = d->header->offset();    int horizontalPosition = d->header->sectionPosition(index.column());    int cellWidth = d->header->sectionSize(index.column());    if (hint == PositionAtCenter) {        horizontalScrollBar()->setValue(horizontalPosition - ((viewportWidth - cellWidth) / 2));    } else {        if (horizontalPosition - horizontalOffset < 0 || cellWidth > viewportWidth)            horizontalScrollBar()->setValue(horizontalPosition);        else if (horizontalPosition - horizontalOffset + cellWidth > viewportWidth)            horizontalScrollBar()->setValue(horizontalPosition - viewportWidth + cellWidth);    }}/*!  \reimp*/void QTreeView::timerEvent(QTimerEvent *event){    Q_D(QTreeView);    if (event->timerId() == d->columnResizeTimerID) {        updateGeometries();        killTimer(d->columnResizeTimerID);        d->columnResizeTimerID = 0;        QRect rect;        int viewportHeight = d->viewport->height();        int viewportWidth = d->viewport->width();        for (int i = d->columnsToUpdate.size() - 1; i >= 0; --i) {            int column = d->columnsToUpdate.at(i);            int x = columnViewportPosition(column);            if (isRightToLeft())                rect |= QRect(0, 0, x + columnWidth(column), viewportHeight);            else                rect |= QRect(x, 0, viewportWidth - x, viewportHeight);        }        d->viewport->update(rect.normalized());        d->columnsToUpdate.clear();    } else if (event->timerId() == d->openTimer.timerId()) {        QPoint pos = d->viewport->mapFromGlobal(QCursor::pos());        if (state() == QAbstractItemView::DraggingState            && d->viewport->rect().contains(pos)) {            QModelIndex index = indexAt(pos);            setExpanded(index, !isExpanded(index));        }        d->openTimer.stop();    }    QAbstractItemView::timerEvent(event);}/*!  \reimp*/#ifndef QT_NO_DRAGANDDROPvoid QTreeView::dragMoveEvent(QDragMoveEvent *event){    Q_D(QTreeView);    if (d->autoExpandDelay >= 0)        d->openTimer.start(d->autoExpandDelay, this);    QAbstractItemView::dragMoveEvent(event);}#endif/*!  \reimp*/bool QTreeView::viewportEvent(QEvent *event){    Q_D(QTreeView);    switch (event->type()) {    case QEvent::HoverEnter:    case QEvent::HoverLeave:    case QEvent::HoverMove: {        QHoverEvent *he = static_cast<QHoverEvent*>(event);        int oldBranch = d->hoverBranch;        d->hoverBranch = d->itemDecorationAt(he->pos());        if (oldBranch != d->hoverBranch) {            QRect oldRect = visualRect(d->modelIndex(oldBranch));            QRect newRect = visualRect(d->modelIndex(d->hoverBranch));            viewport()->update(oldRect.left() - d->indent, oldRect.top(), d->indent, oldRect.height());            viewport()->update(newRect.left() - d->indent, newRect.top(), d->indent, newRect.height());        }        break; }    default:        break;    }    return QAbstractItemView::viewportEvent(event);

⌨️ 快捷键说明

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