qgraphicsitem.cpp

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

CPP
1,909
字号
/******************************************************************************** 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.******************************************************************************//*!    \class QGraphicsItem    \brief The QGraphicsItem class is the base class for all graphical    items in a QGraphicsScene.    \since 4.2    \ingroup multimedia    It provides a light-weight foundation for writing your own custom items.    This includes defining the item's geometry, collision detection, its    painting implementation and item interaction through its event handlers.    QGraphicsItem is part of \l{The Graphics View Framework}    \img graphicsview-items.png    For convenience, Qt provides a set of standard graphics items for the most    common shapes. These are:    \list    \o QGraphicsEllipseItem provides an ellipse item    \o QGraphicsLineItem provides a line item    \o QGraphicsPathItem provides an arbitrary path item    \o QGraphicsPixmapItem provides a pixmap item    \o QGraphicsPolygonItem provides a polygon item    \o QGraphicsRectItem provides a rectangular item    \o QGraphicsTextItem provides a text item    \endlist    All of an item's geometric information is based on its local coordinate    system. The item's position, pos(), is the only function that does not    operate in local coordinates, as it returns a position in parent    coordinates. {The Graphics View Coordinate System} describes the coordinate    system in detail.    You can set whether an item should be visible (i.e., drawn, and accepting    events), by calling setVisible(). Hiding an item will also hide its    children. Similarly, you can enable or disable an item by calling    setEnabled(). If you disable an item, all its children will also be    disabled. By default, items are both visible and enabled. To toggle    whether an item is selected or not, first enable selection by setting    the ItemIsSelectable flag, and then call setSelected(). Normally,    selection is toggled by the scene, as a result of user interaction.    To write your own graphics item, you first create a subclass of    QGraphicsItem, and then start by implementing its two pure virtual public    functions: boundingRect(), which returns an estimate of the area painted    by the item, and paint(), which implements the actual painting. For    example:    \code        class SimpleItem : public QGraphicsItem        {        public:            QRectF boundingRect() const            {                qreal penWidth = 1;                return QRectF(-10 - penWidth / 2, -10 - penWidth / 2,                              20 + penWidth / 2, 20 + penWidth / 2);            }            void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,                       QWidget *widget)            {                painter->drawRoundRect(-10, -10, 20, 20);            }        };    \endcode    The boundingRect() function has many different purposes. QGraphicsScene    bases its item index on boundingRect(), and QGraphicsView uses it both for    culling invisible items, and for determining the area that needs to be    recomposed when drawing overlapping items. In addition, QGraphicsItem's    collision detection mechanisms use boundingRect() to provide an efficient    cut-off. The fine grained collision algorithm in collidesWithItem() is based    on calling shape(), which returns an accurate outline of the item's shape    as a QPainterPath.    Collision detection can be done in two ways:    \list 1    \o Reimplement shape() to return an accurate shape for your item, and rely    on the default implementation of collidesWithItem() to do shape-shape    intersection. This can be rather expensive if the shapes are complex.    \o Reimplement collidesWithItem() to provide your own custom item and shape    collision algorithm.    \endlist    The contains() function can be called to determine whether the item \e    contains a point or not. This function can also be reimplemented by the    item. The default behavior of contains() is based on calling shape().    Items can contain other items, and also be contained by other items. All    items can have a parent item and a list of children. Unless the item has    no parent, its position is in \e parent coordinates (i.e., the parent's    local coordinates). Parent items propagate both their position and their    transformation to all children.    \img graphicsview-parentchild.png    QGraphicsItem supports affine transformations in addition to its base    position, pos(). To change the item's transformation, you can either pass    a transformation matrix to setMatrix(), or call one of the convenience    functions rotate(), scale(), translate(), or shear(). Item transformations    accumulate from parent to child, so if both a parent and child item are    rotated 90 degrees, the child's total transformation will be 180 degrees.    Similarly, if the item's parent is scaled to 2x its original size, its    children will also be twice as large. An item's transformation does not    affect its own local geometry; all geometry functions (e.g., contains(),    update(), and all the mapping functions) still operate in local    coordinates. For convenience, QGraphicsItem provides the functions    sceneMatrix(), which returns the item's total transformation matrix    (including its position and all parents' positions and transformations),    and scenePos(), which returns its position in scene coordinates. To reset    an item's matrix, call resetMatrix().    The paint() function is called by QGraphicsView to paint the item's    contents. The item has no background or default fill of its own; whatever    is behind the item will shine through all areas that are not explicitly    painted in this function.  You can call update() to schedule a repaint,    optionally passing the rectangle that needs a repaint. Depending on    whether or not the item is visible in a view, the item may or may not be    repainted; there is no equivalent to QWidget::repaint() in QGraphicsItem.    Items are painted by the view, starting with the parent items and then    drawing children, in ascending stacking order. You can set an item's    stacking order by calling setZValue(), and test it by calling    zValue(), where items with low z-values are painted before items with    high z-values. Stacking order applies to sibling items; parents are always    drawn before their children.    QGraphicsItem receives events from QGraphicsScene through the virtual    function sceneEvent(). This function distributes the most common events    to a set of convenience event handlers:    \list    \o contextMenuEvent() handles context menu events    \o focusInEvent() and focusOutEvent() handle focus in and out events    \o hoverEnterEvent(), hoverMoveEvent(), and hoverLeaveEvent() handles    hover enter, move and leave events    \o inputMethodEvent() handles input events, for accessibility support    \o keyPressEvent() and keyReleaseEvent handle key press and release events    \o mousePressEvent(), mouseMoveEvent(), mouseReleaseEvent(), and    mouseDoubleClickEvent() handles mouse press, move, release, click and    doubleclick events    \endlist    You can filter events for any other item by installing event    filters. This functionaly is separate from from Qt's regular    event filters (see QObject::installEventFilter()), which only    work on subclasses of QObject. After installing your item as an    event filter for another item by calling    installSceneEventFilter(), the filtered events will be received    by the virtual function sceneEventFilter(). You can remove item    event filters by calling removeSceneEventFilter().    Sometimes it's useful to register custom data with an item, be it a custom    item, or a standard item. You can call setData() on any item to store data    in it using a key-value pair (the key being an integer, and the value is a    QVariant). To get custom data from an item, call data(). This    functionality is completely untouched by Qt itself; it is provided for the    user's convenience.    \sa QGraphicsScene, QGraphicsView, {The Graphics View Framework}*//*!    \variable QGraphicsItem::UserType    The lowest permitted type value for custom items (subclasses    of QGraphicsItem or any of the standard items). This value is    used in conjunction with a reimplementation of QGraphicsItem::type()    and declaring a Type enum value. Example:    \code        class CustomItem : public QGraphicsItem        {           ...           enum { Type = UserType + 1 }           int type() const           {               // Enable the use of qgraphicsitem_cast with this item.               return Type;           }           ...        };    \endcode*//*!    \enum QGraphicsItem::GraphicsItemFlag    This enum describes different flags that you can set on an item to    toggle different features in the item's behavior.    All flags are disabled by default.    \value ItemIsMovable The item supports interactive movement using    the mouse. By clicking on the item and then dragging, the item    will move together with the mouse cursor. If the item has    children, all children are also moved. If the item is part of a    selection, all selected items are also moved. This feature is    provided as a convenience through the base implementation of    QGraphicsItem's mouse event handlers.    \value ItemIsSelectable The item supports selection. Enabling this    feature will enable setSelected() to toggle selection for the    item. It will also let the item be selected automatically as a    result of calling QGraphicsScene::setSelectionArea(), by clicking    on an item, or by using rubber band selection in QGraphicsView.    \value ItemIsFocusable The item supports keyboard input focus (i.e., it is    an input item). Enabling this flag will allow the item to accept focus,    which again allows the delivery of key events to    QGraphicsItem::keyPressEvent() and QGraphicsItem::keyReleaseEvent().*//*!    \enum QGraphicsItem::GraphicsItemChange    This enum describes the state changes that are notified by    QGraphicsItem::itemChange(). The notifications are sent as the state    changes, and in some cases, adjustments can be made (see the documentation    for each change for details).    Note: Be careful with calling functions on the QGraphicsItem itself inside    itemChange(), as certain function calls can lead to unwanted    recursion. For example, you cannot call setPos() in itemChange() on an    ItemPositionChange notification, as the setPos() function will again call    itemChange(ItemPositionChange). Instead, you can return the new, adjusted    position from itemChange().    \value ItemEnabledChange The item's enabled state changes. If the item is    presently enabled, it will become disabled, and vice verca. The value    argument is the new enabled state (i.e., true or false). Do not call    setEnabled() in itemChange() as this notification is delivered. Instead,    you can return the new state from itemChange().    \value ItemMatrixChange The item's matrix changes. This notification is    only sent when the item's local matrix changes (i.e., as a result of    calling setMatrix(), or one of the convenience transformation functions,    such as rotate()). The value argument is the new matrix (i.e., a QMatrix);    to get the old matrix, call matrix(). Do not call setMatrix() or any of    the transformation convenience functions in itemChange() as this    notification is delivered; instead, you can return the new matrix from    itemChange().    \value ItemPositionChange The item's position changes. This notification    is only sent when the item's local position changes, relative to its    parent, has changed (i.e., as a result of calling setPos() or    moveBy()). The value argument is the new position (i.e., a QPointF).    You can call pos() to get the original position. Do not call setPos() or    moveBy() in itemChange() as this notification is delivered; instead, you    can return the new, adjusted position from itemChange().    \value ItemSelectedChange The item's selected state changes. If the item    is presently selected, it will become unselected, and vice verca. The    value argument is the new selected state (i.e., true or false). Do not    call setSelected() in itemChange() as this notification is delivered();    instead, you can return the new selected state from itemChange().    \value ItemVisibleChange The item's visible state changes. If the item is    presently visible, it will become invisible, and vice verca. The value    argument is the new visible state (i.e., true or false). Do not call    setVisible() in itemChange() as this notification is delivered; instead,    you can return the new visible state from itemChange().    \value ItemParentChange The item's parent changes. The value argument is    the new parent item (i.e., a QGraphicsItem pointer).  Do not call    setParentItem() in itemChange() as this notification is delivered;    instead, you can return the new parent from itemChange().    \value ItemChildAddedChange A child is added to this item. The value    argument is the new child item (i.e., a QGraphicsItem pointer). Do not    pass this item to any item's setParentItem() function as this notification    is delivered. The return value is unused; you cannot adjust anything in    this notification. Note that the new child might not be fully constructed    when this notification is sent; calling pure virtual functions on    the child can lead to a crash.    \value ItemChildRemovedChange A child is removed from this item. The value    argument is the child item that is about to be removed (i.e., a    QGraphicsItem pointer). The return value is unused; you cannot adjust    anything in this notification.*//*!    \enum QGraphicsItem::Extension    \internal    Note: This is provided as a hook to avoid future problems related    to adding virtual functions. See also extension(),    supportsExtension() and setExtension().*/#include "qgraphicsitem.h"#ifndef QT_NO_GRAPHICSVIEW#include "qgraphicsscene.h"#include "qgraphicsscene_p.h"#include "qgraphicssceneevent.h"#include "qgraphicsview.h"#include <QtCore/qbitarray.h>#include <QtCore/qdebug.h>#include <QtCore/qpoint.h>#include <QtCore/qtimer.h>#include <QtCore/qvariant.h>#include <QtGui/qapplication.h>#include <QtGui/qbitmap.h>#include <QtGui/qpainter.h>#include <QtGui/qpainterpath.h>#include <QtGui/qstyleoption.h>#include <QtGui/qevent.h>#include <private/qgraphicsitem_p.h>#include <private/qtextcontrol_p.h>#include <private/qtextengine_p.h>#include <math.h>/*    ### Move this into QGraphicsItemPrivate */class QGraphicsItemCustomDataStore{public:    QMap<const QGraphicsItem *, QMap<int, QVariant> > data;};Q_GLOBAL_STATIC(QGraphicsItemCustomDataStore, qt_dataStore);/*!    \internal    Propagates updates to \a item and all its children.*/static void qt_graphicsItem_fullUpdate(QGraphicsItem *item){    item->update();    foreach (QGraphicsItem *child, item->children())        qt_graphicsItem_fullUpdate(child);}/*!    \internal    Returns a QPainterPath of \a path when stroked with the \a pen.    Ignoring dash pattern.*/static QPainterPath qt_graphicsItem_shapeFromPath(const QPainterPath &path, const QPen &pen){    // We unfortunately need this hack as QPainterPathStroker will set a width of 1.0    // if we pass a value of 0.0 to QPainterPathStroker::setWidth()    const qreal penWidthZero = qreal(0.00000001);    if (path == QPainterPath())        return path;

⌨️ 快捷键说明

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