📄 qgraphicsitem.cpp
字号:
/******************************************************************************** Copyright (C) 1992-2007 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://trolltech.com/products/qt/licenses/licensing/opensource/**** If you are unsure which license is appropriate for your use, please** review the following information:** http://trolltech.com/products/qt/licenses/licensing/licensingoverview** or contact the sales department at sales@trolltech.com.**** In addition, as a special exception, Trolltech gives you certain** additional rights. These rights are described in the Trolltech GPL** Exception version 1.0, which can be found at** http://www.trolltech.com/products/qt/gplexception/ and in the file** GPL_EXCEPTION.txt in this package.**** In addition, as a special exception, Trolltech, as the sole copyright** holder for Qt Designer, grants users of the Qt/Eclipse Integration** plug-in the right for the Qt/Eclipse Integration to link to** functionality provided by Qt Designer and its related libraries.**** Trolltech reserves all rights not expressly granted herein.**** 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 QGraphicsSimpleTextItem provides a simple text label item \o QGraphicsTextItem provides an advanced text browser 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. QGraphicsScene expects all items boundingRect() and shape() to remain unchanged unless it is notified. If you want to change an item's geometry in any way, you must first call prepareGeometryChange() to allow QGraphicsScene to update its bookkeeping. 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 setTransform(), 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 sceneTransform(), 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 resetTransform(). 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(). \value ItemClipsToShape The item clips (i.e., restricts) its own painting to inside its shape. Its paintEvent() function cannot draw outside its shape. For complex shapes, this function can be expensive. It is disabled by default. This behavior is enforced by QGraphicsView::drawItems() or QGraphicsScene::drawItems(). This flag was introduced in Qt 4.3. \value ItemClipsChildrenToShape The item clips the painting of all its descendents to its own shape. Items that are either direct or indirect children of this item cannot draw outside this item's shape. By default, this flag is disabled; children can draw anywhere. This behavior is enforced by QGraphicsView::drawItems() or QGraphicsScene::drawItems(). This flag was introduced in Qt 4.3. \value ItemIgnoresTransformations The item ignores inherited transformations (i.e., its position is still relative to its parent, but the parent or view rotation, zoom or shear transformations are ignored). This flag is particularly useful for text label items, which can become unreadable when the view zooms away from the scene. By default, this flag is disabled. This flag was introduced in Qt 4.3.*//*! \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 affine transformation matrix is changing. This value is obsolete; you can use ItemTransformChange instead. \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(). After this notification, QGraphicsItem immediately sends the ItemPositionHasChanged notification if the position changed. \value ItemPositionHasChanged The item's position has changed. This notification is only sent after the item's local position, relative to its parent, has changed. The value argument is the new position (the same as pos()), and QGraphicsItem ignores the return value for this notification (i.e., a read-only notification). \value ItemTransformChange The item's transformation matrix changes. This notification is only sent when the item's local transformation matrix changes (i.e., as a result of calling setTransform(), or one of the convenience transformation functions, such as rotate()). The value argument is the new matrix (i.e., a QTransform); to get the old matrix, call transform(). Do not call setTransform() or any of the transformation convenience functions in itemChange() as this notification is delivered; instead, you can return the new matrix from itemChange(). \value ItemTransformHasChanged The item's transformation matrix has changed. This notification is only sent after the item's local trasformation matrix has changed. The value argument is the new matrix (same as transform()), and QGraphicsItem ignores the return value for this notification (i.e., a read-only notification). \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. \value ItemSceneChange The item is moved to a new scene. This notification is also sent when the item is added to its initial scene, and when it is removed. The value argument is the new scene (i.e., a QGraphicsScene pointer), or a null pointer if the item is removed from a scene. Do not override this change by passing this item to QGraphicsScene::addItem() as
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -