diff options
Diffstat (limited to 'src/declarative')
74 files changed, 1590 insertions, 1017 deletions
diff --git a/src/declarative/3rdparty/3rdparty.pri b/src/declarative/3rdparty/3rdparty.pri deleted file mode 100644 index fbdcc11..0000000 --- a/src/declarative/3rdparty/3rdparty.pri +++ /dev/null @@ -1,7 +0,0 @@ -INCLUDEPATH += $$PWD - -HEADERS += \ - $$PWD/qlistmodelinterface_p.h\ - -SOURCES += \ - $$PWD/qlistmodelinterface.cpp \ diff --git a/src/declarative/QmlChanges.txt b/src/declarative/QmlChanges.txt index 0df5f10..8b6b83f 100644 --- a/src/declarative/QmlChanges.txt +++ b/src/declarative/QmlChanges.txt @@ -1,8 +1,9 @@ ============================================================================= The changes below are pre Qt 4.7.0 RC +QDeclarativeView + - initialSize() function added TextInput and TextEdit: - - showInputPanelOnFocus property added - openSoftwareInputPanel() and closeSoftwareInputPanel() functions added Flickable: - overShoot is replaced by boundsBehavior enumeration diff --git a/src/declarative/debugger/qdeclarativedebugtrace_p.h b/src/declarative/debugger/qdeclarativedebugtrace_p.h index 5ba49a8..704c49a 100644 --- a/src/declarative/debugger/qdeclarativedebugtrace_p.h +++ b/src/declarative/debugger/qdeclarativedebugtrace_p.h @@ -50,7 +50,7 @@ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE class QUrl; -class QDeclarativeDebugTrace : public QDeclarativeDebugService +class Q_AUTOTEST_EXPORT QDeclarativeDebugTrace : public QDeclarativeDebugService { public: enum EventType { diff --git a/src/declarative/declarative.pro b/src/declarative/declarative.pro index 8037a16..510e7a5 100644 --- a/src/declarative/declarative.pro +++ b/src/declarative/declarative.pro @@ -20,7 +20,6 @@ include(../qbase.pri) #DESTDIR=. #modules -include(3rdparty/3rdparty.pri) include(util/util.pri) include(graphicsitems/graphicsitems.pri) include(qml/qml.pri) diff --git a/src/declarative/graphicsitems/qdeclarativeanchors.cpp b/src/declarative/graphicsitems/qdeclarativeanchors.cpp index aa53aba..6796977 100644 --- a/src/declarative/graphicsitems/qdeclarativeanchors.cpp +++ b/src/declarative/graphicsitems/qdeclarativeanchors.cpp @@ -53,6 +53,30 @@ QT_BEGIN_NAMESPACE //TODO: should we cache relationships, so we don't have to check each time (parent-child or sibling)? //TODO: support non-parent, non-sibling (need to find lowest common ancestor) +static qreal hcenter(QGraphicsItem *i) +{ + QGraphicsItemPrivate *item = QGraphicsItemPrivate::get(i); + + qreal width = item->width(); + int iw = width; + if (iw % 2) + return (width + 1) / 2; + else + return width / 2; +} + +static qreal vcenter(QGraphicsItem *i) +{ + QGraphicsItemPrivate *item = QGraphicsItemPrivate::get(i); + + qreal height = item->height(); + int ih = height; + if (ih % 2) + return (height + 1) / 2; + else + return height / 2; +} + //### const item? //local position static qreal position(QGraphicsObject *item, QDeclarativeAnchorLine::AnchorLine anchorLine) @@ -73,10 +97,10 @@ static qreal position(QGraphicsObject *item, QDeclarativeAnchorLine::AnchorLine ret = item->y() + d->height(); break; case QDeclarativeAnchorLine::HCenter: - ret = item->x() + d->width()/2; + ret = item->x() + hcenter(item); break; case QDeclarativeAnchorLine::VCenter: - ret = item->y() + d->height()/2; + ret = item->y() + vcenter(item); break; case QDeclarativeAnchorLine::Baseline: if (d->isDeclarativeItem) @@ -108,10 +132,10 @@ static qreal adjustedPosition(QGraphicsObject *item, QDeclarativeAnchorLine::Anc ret = d->height(); break; case QDeclarativeAnchorLine::HCenter: - ret = d->width()/2; + ret = hcenter(item); break; case QDeclarativeAnchorLine::VCenter: - ret = d->height()/2; + ret = vcenter(item); break; case QDeclarativeAnchorLine::Baseline: if (d->isDeclarativeItem) @@ -192,14 +216,14 @@ void QDeclarativeAnchorsPrivate::centerInChanged() QGraphicsItemPrivate *itemPrivate = QGraphicsItemPrivate::get(item); if (centerIn == item->parentItem()) { QGraphicsItemPrivate *parentPrivate = QGraphicsItemPrivate::get(item->parentItem()); - QPointF p((parentPrivate->width() - itemPrivate->width()) / 2. + hCenterOffset, - (parentPrivate->height() - itemPrivate->height()) / 2. + vCenterOffset); + QPointF p(hcenter(item->parentItem()) - hcenter(item) + hCenterOffset, + vcenter(item->parentItem()) - vcenter(item) + vCenterOffset); setItemPos(p); } else if (centerIn->parentItem() == item->parentItem()) { QGraphicsItemPrivate *centerPrivate = QGraphicsItemPrivate::get(centerIn); - QPointF p(centerIn->x() + (centerPrivate->width() - itemPrivate->width()) / 2. + hCenterOffset, - centerIn->y() + (centerPrivate->height() - itemPrivate->height()) / 2. + vCenterOffset); + QPointF p(centerIn->x() + hcenter(centerIn) - hcenter(item) + hCenterOffset, + centerIn->y() + vcenter(centerIn) - vcenter(item) + vCenterOffset); setItemPos(p); } @@ -535,9 +559,9 @@ void QDeclarativeAnchorsPrivate::updateVerticalAnchors() //Handle vCenter if (vCenter.item == item->parentItem()) { setItemY(adjustedPosition(vCenter.item, vCenter.anchorLine) - - itemPrivate->height()/2 + vCenterOffset); + - vcenter(item) + vCenterOffset); } else if (vCenter.item->parentItem() == item->parentItem()) { - setItemY(position(vCenter.item, vCenter.anchorLine) - itemPrivate->height()/2 + vCenterOffset); + setItemY(position(vCenter.item, vCenter.anchorLine) - vcenter(item) + vCenterOffset); } } else if (usedAnchors & QDeclarativeAnchors::BaselineAnchor) { //Handle baseline @@ -604,9 +628,9 @@ void QDeclarativeAnchorsPrivate::updateHorizontalAnchors() } else if (usedAnchors & QDeclarativeAnchors::HCenterAnchor) { //Handle hCenter if (hCenter.item == item->parentItem()) { - setItemX(adjustedPosition(hCenter.item, hCenter.anchorLine) - itemPrivate->width()/2 + hCenterOffset); + setItemX(adjustedPosition(hCenter.item, hCenter.anchorLine) - hcenter(item) + hCenterOffset); } else if (hCenter.item->parentItem() == item->parentItem()) { - setItemX(position(hCenter.item, hCenter.anchorLine) - itemPrivate->width()/2 + hCenterOffset); + setItemX(position(hCenter.item, hCenter.anchorLine) - hcenter(item) + hCenterOffset); } } diff --git a/src/declarative/graphicsitems/qdeclarativeanimatedimage.cpp b/src/declarative/graphicsitems/qdeclarativeanimatedimage.cpp index a05e426..d8527d3 100644 --- a/src/declarative/graphicsitems/qdeclarativeanimatedimage.cpp +++ b/src/declarative/graphicsitems/qdeclarativeanimatedimage.cpp @@ -63,22 +63,32 @@ QT_BEGIN_NAMESPACE \inherits Image \since 4.7 - This item provides for playing animations stored as images containing a series of frames, - such as GIF files. The full list of supported formats can be determined with - QMovie::supportedFormats(). + The AnimatedImage element provides for playing animations stored as images containing a series of frames, + such as GIF files. + + The full list of supported formats can be determined with QMovie::supportedFormats(). \table \row \o \image animatedimageitem.gif \o \qml -Item { - width: anim.width; height: anim.height+8 - AnimatedImage { id: anim; source: "pics/games-anim.gif" } - Rectangle { color: "red"; width: 4; height: 8; y: anim.height - x: (anim.width-width)*anim.currentFrame/(anim.frameCount-1) + import Qt 4.7 + + Rectangle { + width: animation.width; height: animation.height + 8 + + AnimatedImage { id: animation; source: "animation.gif" } + + Rectangle { + property int frames: animation.frameCount + + width: 4; height: 8 + x: (animation.width - width) * animation.currentFrame / frames + y: animation.height + color: "red" + } } -} \endqml \endtable */ @@ -96,7 +106,7 @@ QDeclarativeAnimatedImage::~QDeclarativeAnimatedImage() /*! \qmlproperty bool AnimatedImage::paused - This property holds whether the animated image is paused or not + This property holds whether the animated image is paused. Defaults to false, and can be set to true when you want to pause. */ @@ -120,7 +130,7 @@ void QDeclarativeAnimatedImage::setPaused(bool pause) } /*! \qmlproperty bool AnimatedImage::playing - This property holds whether the animated image is playing or not + This property holds whether the animated image is playing. Defaults to true, so as to start playing immediately. */ diff --git a/src/declarative/graphicsitems/qdeclarativeborderimage.cpp b/src/declarative/graphicsitems/qdeclarativeborderimage.cpp index 1f1e453..cf458da 100644 --- a/src/declarative/graphicsitems/qdeclarativeborderimage.cpp +++ b/src/declarative/graphicsitems/qdeclarativeborderimage.cpp @@ -138,7 +138,7 @@ QDeclarativeBorderImage::~QDeclarativeBorderImage() BorderImage can handle any image format supported by Qt, loaded from any URL scheme supported by Qt. - It can also handle .sci files, which are a Qml-specific format. A .sci file uses a simple text-based format that specifies + It can also handle .sci files, which are a QML-specific format. A .sci file uses a simple text-based format that specifies the borders, the image file and the tile rules. The following .sci file sets the borders to 10 on each side for the image \c picture.png: diff --git a/src/declarative/graphicsitems/qdeclarativeflickable.cpp b/src/declarative/graphicsitems/qdeclarativeflickable.cpp index 10dc0f8..fdc1444 100644 --- a/src/declarative/graphicsitems/qdeclarativeflickable.cpp +++ b/src/declarative/graphicsitems/qdeclarativeflickable.cpp @@ -351,6 +351,8 @@ void QDeclarativeFlickablePrivate::updateBeginningEnd() Flickable places its children on a surface that can be dragged and flicked. \code + import Qt 4.7 + Flickable { width: 200; height: 200 contentWidth: image.width; contentHeight: image.height @@ -1039,11 +1041,11 @@ QDeclarativeListProperty<QGraphicsObject> QDeclarativeFlickable::flickableChildr The \c boundsBehavior can be one of: \list - \o \e Flickable.StopAtBounds - the contents can not be dragged beyond the boundary + \o Flickable.StopAtBounds - the contents can not be dragged beyond the boundary of the flickable, and flicks will not overshoot. - \o \e Flickable.DragOverBounds - the contents can be dragged beyond the boundary + \o Flickable.DragOverBounds - the contents can be dragged beyond the boundary of the Flickable, but flicks will not overshoot. - \o \e Flickable.DragAndOvershootBounds (default) - the contents can be dragged + \o Flickable.DragAndOvershootBounds (default) - the contents can be dragged beyond the boundary of the Flickable, and can overshoot the boundary when flicked. \endlist diff --git a/src/declarative/graphicsitems/qdeclarativeflipable.cpp b/src/declarative/graphicsitems/qdeclarativeflipable.cpp index d926119..8c9d2dd 100644 --- a/src/declarative/graphicsitems/qdeclarativeflipable.cpp +++ b/src/declarative/graphicsitems/qdeclarativeflipable.cpp @@ -74,7 +74,7 @@ public: \inherits Item Flipable is an item that can be visibly "flipped" between its front and - back sides. It is used together with Rotation and State/Transition to + back sides. It is used together with \l Rotation and \l {State}/\l {Transition} to produce a flipping effect. Here is a Flipable that flips whenever it is clicked: @@ -83,10 +83,12 @@ public: \image flipable.gif - The Rotation element is used to specify the angle and axis of the flip, - and the State defines the changes in angle which produce the flipping - effect. Finally, the Transition creates the animation that changes the + The \l Rotation element is used to specify the angle and axis of the flip, + and the \l State defines the changes in angle which produce the flipping + effect. Finally, the \l Transition creates the animation that changes the angle over one second. + + \sa {declarative/ui-components/flipable}{Flipable example} */ /*! diff --git a/src/declarative/graphicsitems/qdeclarativegridview.cpp b/src/declarative/graphicsitems/qdeclarativegridview.cpp index 906f1fc..3792595 100644 --- a/src/declarative/graphicsitems/qdeclarativegridview.cpp +++ b/src/declarative/graphicsitems/qdeclarativegridview.cpp @@ -108,6 +108,7 @@ public: , highlightComponent(0), highlight(0), trackedItem(0) , moveReason(Other), buffer(0), highlightXAnimator(0), highlightYAnimator(0) , highlightMoveDuration(150) + , footerComponent(0), footer(0), headerComponent(0), header(0) , bufferMode(BufferBefore | BufferAfter), snapMode(QDeclarativeGridView::NoSnap) , ownModel(false), wrap(false), autoHighlight(true) , fixCurrentVisibility(false), lazyRelease(false), layoutScheduled(false) @@ -128,6 +129,8 @@ public: void createHighlight(); void updateHighlight(); void updateCurrent(int modelIndex); + void updateHeader(); + void updateFooter(); void fixupPosition(); FxGridItem *visibleItem(int modelIndex) const { @@ -230,6 +233,18 @@ public: return visibleItems.count() ? visibleItems.first() : 0; } + int lastVisibleIndex() const { + int lastIndex = -1; + for (int i = visibleItems.count()-1; i >= 0; --i) { + FxGridItem *gridItem = visibleItems.at(i); + if (gridItem->index != -1) { + lastIndex = gridItem->index; + break; + } + } + return lastIndex; + } + // Map a model index to visibleItems list index. // These may differ if removed items are still present in the visible list, // e.g. doing a removal animation @@ -246,16 +261,37 @@ public: return -1; // Not in visibleList } - qreal snapPosAt(qreal pos) { + qreal snapPosAt(qreal pos) const { + Q_Q(const QDeclarativeGridView); qreal snapPos = 0; if (!visibleItems.isEmpty()) { pos += rowSize()/2; snapPos = visibleItems.first()->rowPos() - visibleIndex / columns * rowSize(); snapPos = pos - fmodf(pos - snapPos, qreal(rowSize())); + qreal maxExtent = flow == QDeclarativeGridView::LeftToRight ? -q->maxYExtent() : -q->maxXExtent(); + qreal minExtent = flow == QDeclarativeGridView::LeftToRight ? -q->minYExtent() : -q->minXExtent(); + if (snapPos > maxExtent) + snapPos = maxExtent; + if (snapPos < minExtent) + snapPos = minExtent; } return snapPos; } + FxGridItem *snapItemAt(qreal pos) { + for (int i = 0; i < visibleItems.count(); ++i) { + FxGridItem *item = visibleItems[i]; + if (item->index == -1) + continue; + qreal itemTop = item->rowPos(); + if (item->index == model->count()-1 || (itemTop+rowSize()/2 >= pos)) + return item; + } + if (visibleItems.count() && visibleItems.first()->rowPos() <= pos) + return visibleItems.first(); + return 0; + } + int snapIndex() { int index = currentIndex; for (int i = 0; i < visibleItems.count(); ++i) { @@ -283,6 +319,9 @@ public: scheduleLayout(); } } + } else if ((header && header->item == item) || (footer && footer->item == item)) { + updateHeader(); + updateFooter(); } } @@ -330,6 +369,10 @@ public: QSmoothedAnimation *highlightXAnimator; QSmoothedAnimation *highlightYAnimator; int highlightMoveDuration; + QDeclarativeComponent *footerComponent; + FxGridItem *footer; + QDeclarativeComponent *headerComponent; + FxGridItem *header; enum BufferMode { NoBuffer = 0x00, BufferBefore = 0x01, BufferAfter = 0x02 }; int bufferMode; QDeclarativeGridView::SnapMode snapMode; @@ -412,7 +455,6 @@ void QDeclarativeGridViewPrivate::refill(qreal from, qreal to, bool doBuffer) Q_Q(QDeclarativeGridView); if (!isValid() || !q->isComponentComplete()) return; - itemCount = model->count(); qreal bufferFrom = from - buffer; qreal bufferTo = to + buffer; @@ -522,6 +564,10 @@ void QDeclarativeGridViewPrivate::refill(qreal from, qreal to, bool doBuffer) deferredRelease = true; } if (changed) { + if (header) + updateHeader(); + if (footer) + updateFooter(); if (flow == QDeclarativeGridView::LeftToRight) q->setContentHeight(endPosition() - startPosition()); else @@ -557,7 +603,7 @@ void QDeclarativeGridViewPrivate::layout() { Q_Q(QDeclarativeGridView); layoutScheduled = false; - if (!isValid()) { + if (!isValid() && !visibleItems.count()) { clear(); return; } @@ -579,6 +625,10 @@ void QDeclarativeGridViewPrivate::layout() item->setPosition(colPos, rowPos); } } + if (header) + updateHeader(); + if (footer) + updateFooter(); q->refill(); updateHighlight(); moveReason = Other; @@ -742,6 +792,94 @@ void QDeclarativeGridViewPrivate::updateCurrent(int modelIndex) releaseItem(oldCurrentItem); } +void QDeclarativeGridViewPrivate::updateFooter() +{ + Q_Q(QDeclarativeGridView); + if (!footer && footerComponent) { + QDeclarativeItem *item = 0; + QDeclarativeContext *context = new QDeclarativeContext(qmlContext(q)); + QObject *nobj = footerComponent->create(context); + if (nobj) { + QDeclarative_setParent_noEvent(context, nobj); + item = qobject_cast<QDeclarativeItem *>(nobj); + if (!item) + delete nobj; + } else { + delete context; + } + if (item) { + QDeclarative_setParent_noEvent(item, q->viewport()); + item->setParentItem(q->viewport()); + item->setZValue(1); + QDeclarativeItemPrivate *itemPrivate = static_cast<QDeclarativeItemPrivate*>(QGraphicsItemPrivate::get(item)); + itemPrivate->addItemChangeListener(this, QDeclarativeItemPrivate::Geometry); + footer = new FxGridItem(item, q); + } + } + if (footer) { + if (visibleItems.count()) { + qreal endPos = endPosition(); + if (lastVisibleIndex() == model->count()-1) { + footer->setPosition(0, endPos); + } else { + qreal visiblePos = position() + q->height(); + if (endPos <= visiblePos || footer->endRowPos() < endPos) + footer->setPosition(0, endPos); + } + } else { + qreal endPos = 0; + if (header) { + endPos += flow == QDeclarativeGridView::LeftToRight + ? header->item->height() + : header->item->width(); + } + footer->setPosition(0, endPos); + } + } +} + +void QDeclarativeGridViewPrivate::updateHeader() +{ + Q_Q(QDeclarativeGridView); + if (!header && headerComponent) { + QDeclarativeItem *item = 0; + QDeclarativeContext *context = new QDeclarativeContext(qmlContext(q)); + QObject *nobj = headerComponent->create(context); + if (nobj) { + QDeclarative_setParent_noEvent(context, nobj); + item = qobject_cast<QDeclarativeItem *>(nobj); + if (!item) + delete nobj; + } else { + delete context; + } + if (item) { + QDeclarative_setParent_noEvent(item, q->viewport()); + item->setParentItem(q->viewport()); + item->setZValue(1); + QDeclarativeItemPrivate *itemPrivate = static_cast<QDeclarativeItemPrivate*>(QGraphicsItemPrivate::get(item)); + itemPrivate->addItemChangeListener(this, QDeclarativeItemPrivate::Geometry); + header = new FxGridItem(item, q); + } + } + if (header) { + if (visibleItems.count()) { + qreal startPos = startPosition(); + qreal headerSize = flow == QDeclarativeGridView::LeftToRight + ? header->item->height() + : header->item->width(); + if (visibleIndex == 0) { + header->setPosition(0, startPos - headerSize); + } else { + if (position() <= startPos || header->rowPos() > startPos - headerSize) + header->setPosition(0, startPos - headerSize); + } + } else { + header->setPosition(0, 0); + } + } +} + void QDeclarativeGridViewPrivate::fixupPosition() { moveReason = Other; @@ -753,7 +891,6 @@ void QDeclarativeGridViewPrivate::fixupPosition() void QDeclarativeGridViewPrivate::fixup(AxisData &data, qreal minExtent, qreal maxExtent) { - Q_Q(QDeclarativeGridView); if ((flow == QDeclarativeGridView::TopToBottom && &data == &vData) || (flow == QDeclarativeGridView::LeftToRight && &data == &hData)) return; @@ -761,7 +898,41 @@ void QDeclarativeGridViewPrivate::fixup(AxisData &data, qreal minExtent, qreal m int oldDuration = fixupDuration; fixupDuration = moveReason == Mouse ? fixupDuration : 0; - if (haveHighlightRange && highlightRange == QDeclarativeGridView::StrictlyEnforceRange) { + if (snapMode != QDeclarativeGridView::NoSnap) { + FxGridItem *topItem = snapItemAt(position()+highlightRangeStart); + FxGridItem *bottomItem = snapItemAt(position()+highlightRangeEnd); + qreal pos; + if (topItem && bottomItem && haveHighlightRange && highlightRange == QDeclarativeGridView::StrictlyEnforceRange) { + qreal topPos = qMin(topItem->rowPos() - highlightRangeStart, -maxExtent); + qreal bottomPos = qMax(bottomItem->rowPos() - highlightRangeEnd, -minExtent); + pos = qAbs(data.move + topPos) < qAbs(data.move + bottomPos) ? topPos : bottomPos; + } else if (topItem) { + pos = qMax(qMin(topItem->rowPos() - highlightRangeStart, -maxExtent), -minExtent); + } else if (bottomItem) { + pos = qMax(qMin(bottomItem->rowPos() - highlightRangeStart, -maxExtent), -minExtent); + } else { + fixupDuration = oldDuration; + return; + } + if (currentItem && haveHighlightRange && highlightRange == QDeclarativeGridView::StrictlyEnforceRange) { + updateHighlight(); + qreal currPos = currentItem->rowPos(); + if (pos < currPos + rowSize() - highlightRangeEnd) + pos = currPos + rowSize() - highlightRangeEnd; + if (pos > currPos - highlightRangeStart) + pos = currPos - highlightRangeStart; + } + + qreal dist = qAbs(data.move + pos); + if (dist > 0) { + timeline.reset(data.move); + if (fixupDuration) + timeline.move(data.move, -pos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration/2); + else + timeline.set(data.move, -pos); + vTime = timeline.time(); + } + } else if (haveHighlightRange && highlightRange == QDeclarativeGridView::StrictlyEnforceRange) { if (currentItem) { updateHighlight(); qreal pos = currentItem->rowPos(); @@ -773,26 +944,10 @@ void QDeclarativeGridViewPrivate::fixup(AxisData &data, qreal minExtent, qreal m timeline.reset(data.move); if (viewPos != position()) { - if (fixupDuration) { + if (fixupDuration) timeline.move(data.move, -viewPos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration/2); - } else { - data.move.setValue(-viewPos); - q->viewportMoved(); - } - } - vTime = timeline.time(); - } - } else if (snapMode != QDeclarativeGridView::NoSnap) { - qreal pos = -snapPosAt(-(data.move.value() - highlightRangeStart)) + highlightRangeStart; - pos = qMin(qMax(pos, maxExtent), minExtent); - qreal dist = qAbs(data.move.value() - pos); - if (dist > 0) { - timeline.reset(data.move); - if (fixupDuration) { - timeline.move(data.move, pos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration/2); - } else { - data.move.setValue(pos); - q->viewportMoved(); + else + timeline.set(data.move, -viewPos); } vTime = timeline.time(); } @@ -806,7 +961,6 @@ void QDeclarativeGridViewPrivate::flick(AxisData &data, qreal minExtent, qreal m QDeclarativeTimeLineCallback::Callback fixupCallback, qreal velocity) { Q_Q(QDeclarativeGridView); - moveReason = Mouse; if ((!haveHighlightRange || highlightRange != QDeclarativeGridView::StrictlyEnforceRange) && snapMode == QDeclarativeGridView::NoSnap) { @@ -851,9 +1005,10 @@ void QDeclarativeGridViewPrivate::flick(AxisData &data, qreal minExtent, qreal m qreal accel = deceleration; qreal v2 = v * v; qreal overshootDist = 0.0; - if (maxDistance > 0.0 && v2 / (2.0f * maxDistance) < accel) { + if ((maxDistance > 0.0 && v2 / (2.0f * maxDistance) < accel) || snapMode == QDeclarativeGridView::SnapOneRow) { // + rowSize()/4 to encourage moving at least one item in the flick direction qreal dist = v2 / (accel * 2.0) + rowSize()/4; + dist = qMin(dist, maxDistance); if (v > 0) dist = -dist; data.flickTarget = -snapPosAt(-(data.move.value() - highlightRangeStart) + dist) + highlightRangeStart; @@ -904,28 +1059,43 @@ void QDeclarativeGridViewPrivate::flick(AxisData &data, qreal minExtent, qreal m \inherits Flickable \brief The GridView item provides a grid view of items provided by a model. - The model is typically provided by a QAbstractListModel "C++ model object", - but can also be created directly in QML. + A GridView displays data from models created from built-in QML elements like ListModel + and XmlListModel, or custom model classes defined in C++ that inherit from + QAbstractListModel. + + A GridView has a \l model, which defines the data to be displayed, and + a \l delegate, which defines how the data should be displayed. Items in a + GridView are laid out horizontally or vertically. Grid views are inherently flickable + as GridView inherits from \l Flickable. - The items are laid out top to bottom (vertically) or left to right (horizontally) - and may be flicked to scroll. + For example, if there is a simple list model defined in a file \c ContactModel.qml like this: - The below example creates a very simple grid, using a QML model. + \snippet doc/src/snippets/declarative/gridview/ContactModel.qml 0 - \image gridview.png + Another component can display this model data in a GridView, like this: - \snippet doc/src/snippets/declarative/gridview/gridview.qml 3 + \snippet doc/src/snippets/declarative/gridview/gridview.qml import + \codeline + \snippet doc/src/snippets/declarative/gridview/gridview.qml classdocs simple + \image gridview-simple.png - The model is defined as a ListModel using QML: - \quotefile doc/src/snippets/declarative/gridview/dummydata/ContactModel.qml + Here, the GridView creates a \c ContactModel component for its model, and a \l Column element + (containing \l Image and \ Text elements) for its delegate. The view will create a new delegate + for each item in the model. Notice the delegate is able to access the model's \c name and + \c portrait data directly. - In this case ListModel is a handy way for us to test our UI. In practice - the model would be implemented in C++, or perhaps via a SQL data source. + An improved grid view is shown below. The delegate is visually improved and is moved + into a separate \c contactDelegate component. Also, the currently selected item is highlighted + with a blue \l Rectangle using the \l highlight property, and \c focus is set to \c true + to enable keyboard navigation for the grid view. + + \snippet doc/src/snippets/declarative/gridview/gridview.qml classdocs advanced + \image gridview-highlight.png Delegates are instantiated as needed and may be destroyed at any time. State should \e never be stored in a delegate. - \bold Note that views do not enable \e clip automatically. If the view + \note Views do not enable \e clip automatically. If the view is not clipped by another item or the screen, it will be necessary to set \e {clip: true} in order to have the out of view items clipped nicely. @@ -943,11 +1113,13 @@ QDeclarativeGridView::~QDeclarativeGridView() d->clear(); if (d->ownModel) delete d->model; + delete d->header; + delete d->footer; } /*! \qmlattachedproperty bool GridView::isCurrentItem - This attched property is true if this delegate is the current item; otherwise false. + This attached property is true if this delegate is the current item; otherwise false. It is attached to each instance of the delegate. */ @@ -971,19 +1143,7 @@ QDeclarativeGridView::~QDeclarativeGridView() The example below ensures that the animation completes before the item is removed from the grid. - \code - Component { - id: myDelegate - Item { - id: wrapper - GridView.onRemove: SequentialAnimation { - PropertyAction { target: wrapper; property: "GridView.delayRemove"; value: true } - NumberAnimation { target: wrapper; property: "scale"; to: 0; duration: 250; easing.type: Easing.InOutQuad } - PropertyAction { target: wrapper; property: "GridView.delayRemove"; value: false } - } - } - } - \endcode + \snippet doc/src/snippets/declarative/gridview/gridview.qml delayRemove */ /*! @@ -1001,10 +1161,10 @@ QDeclarativeGridView::~QDeclarativeGridView() \qmlproperty model GridView::model This property holds the model providing data for the grid. - The model provides a set of data that is used to create the items - for the view. For large or dynamic datasets the model is usually - provided by a C++ model object. The C++ model object must be a \l - {QAbstractItemModel} subclass, a VisualModel, or a simple list. + The model provides the set of data that is used to create the items + in the view. Models can be created directly in QML using \l ListModel, \l XmlListModel + or \l VisualItemModel, or provided by C++ model classes. If a C++ model class is + used, it must be a subclass of \l QAbstractItemModel or a simple list. \sa {qmlmodels}{Data Models} */ @@ -1079,11 +1239,11 @@ void QDeclarativeGridView::setModel(const QVariant &model) that is not needed for the normal display of the delegate in a \l Loader which can load additional elements when needed. - Note that the GridView will layout the items based on the size of the root item + The GridView will layout the items based on the size of the root item in the delegate. - Here is an example delegate: - \snippet doc/src/snippets/declarative/gridview/gridview.qml 0 + \note Delegates are instantiated as needed and may be destroyed at any time. + State should \e never be stored in a delegate. */ QDeclarativeComponent *QDeclarativeGridView::delegate() const { @@ -1157,8 +1317,7 @@ QDeclarativeItem *QDeclarativeGridView::currentItem() /*! \qmlproperty Item GridView::highlightItem - \c highlightItem holds the highlight item, which was created - from the \l highlight component. + This holds the highlight item created from the \l highlight component. The highlightItem is managed by the view unless \l highlightFollowsCurrentItem is set to false. @@ -1189,13 +1348,10 @@ int QDeclarativeGridView::count() const \qmlproperty Component GridView::highlight This property holds the component to use as the highlight. - An instance of the highlight component will be created for each view. - The geometry of the resultant component instance will be managed by the view + An instance of the highlight component is created for each view. + The geometry of the resulting component instance will be managed by the view so as to stay with the current item, unless the highlightFollowsCurrentItem property is false. - The below example demonstrates how to make a simple highlight: - \snippet doc/src/snippets/declarative/gridview/gridview.qml 1 - \sa highlightItem, highlightFollowsCurrentItem */ QDeclarativeComponent *QDeclarativeGridView::highlight() const @@ -1218,21 +1374,14 @@ void QDeclarativeGridView::setHighlight(QDeclarativeComponent *highlight) \qmlproperty bool GridView::highlightFollowsCurrentItem This property sets whether the highlight is managed by the view. - If highlightFollowsCurrentItem is true, the highlight will be moved smoothly - to follow the current item. If highlightFollowsCurrentItem is false, the - highlight will not be moved by the view, and must be implemented - by the highlight component, for example: - - \code - Component { - id: myHighlight - Rectangle { - id: wrapper; color: "lightsteelblue"; radius: 4; width: 320; height: 60 - SpringFollow on y { source: wrapper.GridView.view.currentItem.y; spring: 3; damping: 0.2 } - SpringFollow on x { source: wrapper.GridView.view.currentItem.x; spring: 3; damping: 0.2 } - } - } - \endcode + If this property is true, the highlight is moved smoothly + to follow the current item. Otherwise, the + highlight is not moved by the view, and any movement must be implemented + by the highlight. + + Here is a highlight with its motion defined by a \l {SpringFollow} item: + + \snippet doc/src/snippets/declarative/gridview/gridview.qml highlightFollowsCurrentItem */ bool QDeclarativeGridView::highlightFollowsCurrentItem() const { @@ -1290,32 +1439,30 @@ void QDeclarativeGridView::setHighlightMoveDuration(int duration) \qmlproperty real GridView::preferredHighlightEnd \qmlproperty enumeration GridView::highlightRangeMode - These properties set the preferred range of the highlight (current item) - within the view. - - Note that this is the correct way to influence where the - current item ends up when the view scrolls. For example, if you want the - currently selected item to be in the middle of the list, then set the - highlight range to be where the middle item would go. Then, when the view scrolls, - the currently selected item will be the item at that spot. This also applies to - when the currently selected item changes - it will scroll to within the preferred - highlight range. Furthermore, the behaviour of the current item index will occur - whether or not a highlight exists. - - If highlightRangeMode is set to \e GridView.ApplyRange the view will - attempt to maintain the highlight within the range, however - the highlight can move outside of the range at the ends of the list - or due to a mouse interaction. + These properties define the preferred range of the highlight (for the current item) + within the view. The \c preferredHighlightBegin value must be less than the + \c preferredHighlightEnd value. - If highlightRangeMode is set to \e GridView.StrictlyEnforceRange the highlight will never - move outside of the range. This means that the current item will change - if a keyboard or mouse action would cause the highlight to move - outside of the range. + These properties affect the position of the current item when the view is scrolled. + For example, if the currently selected item should stay in the middle of the + view when it is scrolled, set the \c preferredHighlightBegin and + \c preferredHighlightEnd values to the top and bottom coordinates of where the middle + item would be. If the \c currentItem is changed programmatically, the view will + automatically scroll so that the current item is in the middle of the view. + Furthermore, the behavior of the current item index will occur whether or not a + highlight exists. - The default value is \e GridView.NoHighlightRange. + Valid values for \c highlightRangeMode are: - Note that a valid range requires preferredHighlightEnd to be greater - than or equal to preferredHighlightBegin. + \list + \o GridView.ApplyRange - the view attempts to maintain the highlight within the range. + However, the highlight can move outside of the range at the ends of the view or due + to mouse interaction. + \o GridView.StrictlyEnforceRange - the highlight never moves outside of the range. + The current item changes if a keyboard or mouse action would cause the highlight to move + outside of the range. + \o GridView.NoHighlightRange - this is the default value. + \endlist */ qreal QDeclarativeGridView::preferredHighlightBegin() const { @@ -1370,10 +1517,12 @@ void QDeclarativeGridView::setHighlightRangeMode(HighlightRangeMode mode) \qmlproperty enumeration GridView::flow This property holds the flow of the grid. - Possible values are \c GridView.LeftToRight (default) and \c GridView.TopToBottom. + Possible values: - If \a flow is \c GridView.LeftToRight, the view will scroll vertically. - If \a flow is \c GridView.TopToBottom, the view will scroll horizontally. + \list + \o GridView.LeftToRight (default) - Items are laid out from left to right, and the view scrolls vertically + \o GridView.TopToBottom - Items are laid out from top to bottom, and the view scrolls horizontally + \endlist */ QDeclarativeGridView::Flow QDeclarativeGridView::flow() const { @@ -1405,8 +1554,9 @@ void QDeclarativeGridView::setFlow(Flow flow) \qmlproperty bool GridView::keyNavigationWraps This property holds whether the grid wraps key navigation - If this property is true then key presses to move off of one end of the grid will cause the - selection to jump to the other side. + If this is true, key navigation that would move the current item selection + past one end of the view instead wraps around and moves the selection to + the other end of the view. */ bool QDeclarativeGridView::isWrapEnabled() const { @@ -1463,7 +1613,7 @@ void QDeclarativeGridView::setCacheBuffer(int buffer) \qmlproperty int GridView::cellWidth \qmlproperty int GridView::cellHeight - These properties holds the width and height of each cell in the grid + These properties holds the width and height of each cell in the grid. The default cell size is 100x100. */ @@ -1503,14 +1653,14 @@ void QDeclarativeGridView::setCellHeight(int cellHeight) /*! \qmlproperty enumeration GridView::snapMode - This property determines where the view will settle following a drag or flick. - The allowed values are: + This property determines how the view scrolling will settle following a drag or flick. + The possible values are: \list - \o GridView.NoSnap (default) - the view will stop anywhere within the visible area. - \o GridView.SnapToRow - the view will settle with a row (or column for TopToBottom flow) + \o GridView.NoSnap (default) - the view stops anywhere within the visible area. + \o GridView.SnapToRow - the view settles with a row (or column for \c GridView.TopToBottom flow) aligned with the start of the view. - \o GridView.SnapOneRow - the view will settle no more than one row (or column for TopToBottom flow) + \o GridView.SnapOneRow - the view will settle no more than one row (or column for \c GridView.TopToBottom flow) away from the first visible row at the time the mouse button is released. This mode is particularly useful for moving one page at a time. \endlist @@ -1531,6 +1681,67 @@ void QDeclarativeGridView::setSnapMode(SnapMode mode) } } +/*! + \qmlproperty Component GridView::footer + This property holds the component to use as the footer. + + An instance of the footer component is created for each view. The + footer is positioned at the end of the view, after any items. + + \sa header +*/ +QDeclarativeComponent *QDeclarativeGridView::footer() const +{ + Q_D(const QDeclarativeGridView); + return d->footerComponent; +} + +void QDeclarativeGridView::setFooter(QDeclarativeComponent *footer) +{ + Q_D(QDeclarativeGridView); + if (d->footerComponent != footer) { + if (d->footer) { + delete d->footer; + d->footer = 0; + } + d->footerComponent = footer; + d->updateFooter(); + d->updateGrid(); + emit footerChanged(); + } +} + +/*! + \qmlproperty Component GridView::header + This property holds the component to use as the header. + + An instance of the header component is created for each view. The + header is positioned at the beginning of the view, before any items. + + \sa footer +*/ +QDeclarativeComponent *QDeclarativeGridView::header() const +{ + Q_D(const QDeclarativeGridView); + return d->headerComponent; +} + +void QDeclarativeGridView::setHeader(QDeclarativeComponent *header) +{ + Q_D(QDeclarativeGridView); + if (d->headerComponent != header) { + if (d->header) { + delete d->header; + d->header = 0; + } + d->headerComponent = header; + d->updateHeader(); + d->updateFooter(); + d->updateGrid(); + emit headerChanged(); + } +} + bool QDeclarativeGridView::event(QEvent *event) { Q_D(QDeclarativeGridView); @@ -1597,6 +1808,8 @@ qreal QDeclarativeGridView::minYExtent() const if (d->flow == QDeclarativeGridView::TopToBottom) return QDeclarativeFlickable::minYExtent(); qreal extent = -d->startPosition(); + if (d->header && d->visibleItems.count()) + extent += d->header->item->height(); if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) { extent += d->highlightRangeStart; extent = qMax(extent, -(d->rowPosAt(0) + d->rowSize() - d->highlightRangeEnd)); @@ -1610,13 +1823,17 @@ qreal QDeclarativeGridView::maxYExtent() const if (d->flow == QDeclarativeGridView::TopToBottom) return QDeclarativeFlickable::maxYExtent(); qreal extent; - if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) { + if (!d->model || !d->model->count()) { + extent = 0; + } else if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) { extent = -(d->rowPosAt(d->model->count()-1) - d->highlightRangeStart); if (d->highlightRangeEnd != d->highlightRangeStart) extent = qMin(extent, -(d->endPosition() - d->highlightRangeEnd + 1)); } else { extent = -(d->endPosition() - height()); } + if (d->footer) + extent -= d->footer->item->height(); const qreal minY = minYExtent(); if (extent > minY) extent = minY; @@ -1629,6 +1846,8 @@ qreal QDeclarativeGridView::minXExtent() const if (d->flow == QDeclarativeGridView::LeftToRight) return QDeclarativeFlickable::minXExtent(); qreal extent = -d->startPosition(); + if (d->header && d->visibleItems.count()) + extent += d->header->item->width(); if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) { extent += d->highlightRangeStart; extent = qMax(extent, -(d->rowPosAt(0) + d->rowSize() - d->highlightRangeEnd)); @@ -1642,13 +1861,17 @@ qreal QDeclarativeGridView::maxXExtent() const if (d->flow == QDeclarativeGridView::LeftToRight) return QDeclarativeFlickable::maxXExtent(); qreal extent; - if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) { + if (!d->model || !d->model->count()) { + extent = 0; + } if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) { extent = -(d->rowPosAt(d->model->count()-1) - d->highlightRangeStart); if (d->highlightRangeEnd != d->highlightRangeStart) extent = qMin(extent, -(d->endPosition() - d->highlightRangeEnd + 1)); } else { - extent = -(d->endPosition() - height()); + extent = -(d->endPosition() - width()); } + if (d->footer) + extent -= d->footer->item->width(); const qreal minX = minXExtent(); if (extent > minX) extent = minX; @@ -1789,22 +2012,22 @@ void QDeclarativeGridView::moveCurrentIndexRight() \a mode: \list - \o Beginning - position item at the top (or left for TopToBottom flow) of the view. - \o Center- position item in the center of the view. - \o End - position item at bottom (or right for horizontal orientation) of the view. - \o Visible - if any part of the item is visible then take no action, otherwise + \o GridView.Beginning - position item at the top (or left for \c GridView.TopToBottom flow) of the view. + \o GridView.Center - position item in the center of the view. + \o GridView.End - position item at bottom (or right for horizontal orientation) of the view. + \o GridView.Visible - if any part of the item is visible then take no action, otherwise bring the item into view. - \o Contain - ensure the entire item is visible. If the item is larger than - the view the item is positioned at the top (or left for TopToBottom flow) of the view. + \o GridView.Contain - ensure the entire item is visible. If the item is larger than + the view the item is positioned at the top (or left for \c GridView.TopToBottom flow) of the view. \endlist If positioning the view at the index would cause empty space to be displayed at the beginning or end of the view, the view will be positioned at the boundary. - It is not recommended to use contentX or contentY to position the view + It is not recommended to use \l {Flickable::}{contentX} or \l {Flickable::}{contentY} to position the view at a particular index. This is unreliable since removing items from the start of the view does not cause all other items to be repositioned. - The correct way to bring an item into view is with positionViewAtIndex. + The correct way to bring an item into view is with \c positionViewAtIndex. */ void QDeclarativeGridView::positionViewAtIndex(int index, int mode) { diff --git a/src/declarative/graphicsitems/qdeclarativegridview_p.h b/src/declarative/graphicsitems/qdeclarativegridview_p.h index 2bf154c..021aad9 100644 --- a/src/declarative/graphicsitems/qdeclarativegridview_p.h +++ b/src/declarative/graphicsitems/qdeclarativegridview_p.h @@ -80,6 +80,9 @@ class Q_DECLARATIVE_EXPORT QDeclarativeGridView : public QDeclarativeFlickable Q_PROPERTY(SnapMode snapMode READ snapMode WRITE setSnapMode NOTIFY snapModeChanged) + Q_PROPERTY(QDeclarativeComponent *header READ header WRITE setHeader NOTIFY headerChanged) + Q_PROPERTY(QDeclarativeComponent *footer READ footer WRITE setFooter NOTIFY footerChanged) + Q_ENUMS(HighlightRangeMode) Q_ENUMS(SnapMode) Q_ENUMS(Flow) @@ -142,6 +145,12 @@ public: SnapMode snapMode() const; void setSnapMode(SnapMode mode); + QDeclarativeComponent *footer() const; + void setFooter(QDeclarativeComponent *); + + QDeclarativeComponent *header() const; + void setHeader(QDeclarativeComponent *); + enum PositionMode { Beginning, Center, End, Visible, Contain }; Q_INVOKABLE void positionViewAtIndex(int index, int mode); @@ -172,6 +181,8 @@ Q_SIGNALS: void keyNavigationWrapsChanged(); void cacheBufferChanged(); void snapModeChanged(); + void headerChanged(); + void footerChanged(); protected: virtual bool event(QEvent *event); diff --git a/src/declarative/graphicsitems/qdeclarativeimage.cpp b/src/declarative/graphicsitems/qdeclarativeimage.cpp index 4593cf8..ec08517 100644 --- a/src/declarative/graphicsitems/qdeclarativeimage.cpp +++ b/src/declarative/graphicsitems/qdeclarativeimage.cpp @@ -83,6 +83,8 @@ QT_BEGIN_NAMESPACE that images which do not form part of the user interface have their size bounded via the \l sourceSize property. This is especially important for content that is loaded from external sources or provided by the user. + + \sa {declarative/imageelements/image}{Image example} */ /*! @@ -95,7 +97,7 @@ QT_BEGIN_NAMESPACE Image { source: "pics/star.png" } \endqml - A QDeclarativeImage object can be instantiated in Qml using the tag \l Image. + A QDeclarativeImage object can be instantiated in QML using the tag \l Image. */ QDeclarativeImage::QDeclarativeImage(QDeclarativeItem *parent) @@ -275,11 +277,6 @@ qreal QDeclarativeImage::paintedHeight() const \o Image.Error - an error occurred while loading the image \endlist - Note that a change in the status property does not cause anything to happen - (although it reflects what has happened with the image internally). If you wish - to react to the change in status you need to do it yourself, for example in one - of the following ways: - Use this status to provide an update or respond to the status change in some way. For example, you could: diff --git a/src/declarative/graphicsitems/qdeclarativeimage_p.h b/src/declarative/graphicsitems/qdeclarativeimage_p.h index 5ea700d..fa5b2a9 100644 --- a/src/declarative/graphicsitems/qdeclarativeimage_p.h +++ b/src/declarative/graphicsitems/qdeclarativeimage_p.h @@ -87,8 +87,6 @@ protected: QDeclarativeImage(QDeclarativeImagePrivate &dd, QDeclarativeItem *parent); void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry); void pixmapChange(); - -protected Q_SLOTS: void updatePaintedGeometry(); private: diff --git a/src/declarative/graphicsitems/qdeclarativeitem.cpp b/src/declarative/graphicsitems/qdeclarativeitem.cpp index 134bd6d..18806e7 100644 --- a/src/declarative/graphicsitems/qdeclarativeitem.cpp +++ b/src/declarative/graphicsitems/qdeclarativeitem.cpp @@ -86,8 +86,8 @@ QT_BEGIN_NAMESPACE The Transform elements let you create and control advanced transformations that can be configured independently using specialized properties. - You can assign any number of Transform elements to an Item. Each Transform is applied in order, - one at a time, to the Item it's assigned to. + You can assign any number of Transform elements to an \l Item. Each Transform is applied in order, + one at a time. */ /*! @@ -97,9 +97,11 @@ QT_BEGIN_NAMESPACE The Translate object provides independent control over position in addition to the Item's x and y properties. - The following example moves the Y axis of the Rectangles while still allowing the Row element + The following example moves the Y axis of the \l Rectangle elements while still allowing the \l Row element to lay the items out as if they had not been transformed: \qml + import Qt 4.7 + Row { Rectangle { width: 100; height: 100 @@ -113,6 +115,8 @@ QT_BEGIN_NAMESPACE } } \endqml + + \image translate.png */ /*! @@ -130,9 +134,9 @@ QT_BEGIN_NAMESPACE /*! \qmlclass Scale QGraphicsScale \since 4.7 - \brief The Scale object provides a way to scale an Item. + \brief The Scale element provides a way to scale an Item. - The Scale object gives more control over scaling than using Item's scale property. Specifically, + The Scale element gives more control over scaling than using \l Item's \l{Item::scale}{scale} property. Specifically, it allows a different scale for the x and y axes, and allows the scale to be relative to an arbitrary point. @@ -144,6 +148,8 @@ QT_BEGIN_NAMESPACE transform: Scale { origin.x: 25; origin.y: 25; xScale: 3} } \endqml + + \sa Rotate, Translate */ /*! @@ -171,7 +177,7 @@ QT_BEGIN_NAMESPACE \since 4.7 \brief The Rotation object provides a way to rotate an Item. - The Rotation object gives more control over rotation than using Item's rotation property. + The Rotation object gives more control over rotation than using \l Item's \l{Item::rotation}{rotation} property. Specifically, it allows (z axis) rotation to be relative to an arbitrary point. The following example rotates a Rectangle around its interior point 25, 25: @@ -722,7 +728,7 @@ void QDeclarativeKeyNavigationAttached::keyReleased(QKeyEvent *event, bool post) The signal properties have a \l KeyEvent parameter, named \e event which contains details of the event. If a key is handled \e event.accepted should be set to true to prevent the - event from propagating up the item heirarchy. + event from propagating up the item hierarchy. \code Item { @@ -1629,7 +1635,7 @@ void QDeclarativeItemPrivate::data_append(QDeclarativeListProperty<QObject> *pro QObject *QDeclarativeItemPrivate::resources_at(QDeclarativeListProperty<QObject> *prop, int index) { - QObjectList children = prop->object->children(); + const QObjectList children = prop->object->children(); if (index < children.count()) return children.at(index); else @@ -2387,6 +2393,28 @@ void QDeclarativeItem::forceFocus() } } + +/*! + \qmlmethod Item::childAt(real x, real y) + + Returns the visible child item at point (\a x, \a y), which is in this + item's coordinate system, or \c null if there is no such item. + */ +QDeclarativeItem *QDeclarativeItem::childAt(qreal x, qreal y) const +{ + const QList<QGraphicsItem *> children = childItems(); + for (int i = children.count()-1; i >= 0; --i) { + if (QDeclarativeItem *child = qobject_cast<QDeclarativeItem *>(children.at(i))) { + if (child->isVisible() && child->x() <= x + && child->x() + child->width() >= x + && child->y() <= y + && child->y() + child->height() >= y) + return child; + } + } + return 0; +} + void QDeclarativeItemPrivate::focusChanged(bool flag) { Q_Q(QDeclarativeItem); diff --git a/src/declarative/graphicsitems/qdeclarativeitem.h b/src/declarative/graphicsitems/qdeclarativeitem.h index 77e316b..4f420f8 100644 --- a/src/declarative/graphicsitems/qdeclarativeitem.h +++ b/src/declarative/graphicsitems/qdeclarativeitem.h @@ -148,6 +148,7 @@ public: Q_INVOKABLE QScriptValue mapFromItem(const QScriptValue &item, qreal x, qreal y) const; Q_INVOKABLE QScriptValue mapToItem(const QScriptValue &item, qreal x, qreal y) const; Q_INVOKABLE void forceFocus(); + Q_INVOKABLE QDeclarativeItem *childAt(qreal x, qreal y) const; Q_SIGNALS: void childrenChanged(); diff --git a/src/declarative/graphicsitems/qdeclarativelayoutitem.cpp b/src/declarative/graphicsitems/qdeclarativelayoutitem.cpp index 4add66d..38d5f59 100644 --- a/src/declarative/graphicsitems/qdeclarativelayoutitem.cpp +++ b/src/declarative/graphicsitems/qdeclarativelayoutitem.cpp @@ -58,7 +58,10 @@ QT_BEGIN_NAMESPACE taking its size hints into account, and you can propagate this to the other elements in your UI via anchors and bindings. This is a QGraphicsLayoutItem subclass, and its properties merely expose the QGraphicsLayoutItem functionality to QML. - See the QGraphicsLayoutItem documentation for further details. + + The \l{declarative/cppextensions/qgraphicslayouts/layoutitem}{LayoutItem example} + demonstrates how a LayoutItem can be used within a \l{Graphics View Framework}{Graphics View} + scene. */ /*! diff --git a/src/declarative/graphicsitems/qdeclarativelistview.cpp b/src/declarative/graphicsitems/qdeclarativelistview.cpp index 78c56d6..dcf18af 100644 --- a/src/declarative/graphicsitems/qdeclarativelistview.cpp +++ b/src/declarative/graphicsitems/qdeclarativelistview.cpp @@ -427,6 +427,12 @@ public: scheduleLayout(); } } + if ((header && header->item == item) || (footer && footer->item == item)) { + updateHeader(); + updateFooter(); + } + if (currentItem && currentItem->item == item) + updateHighlight(); if (trackedItem && trackedItem->item == item) q->trackedPositionChanged(); } @@ -731,7 +737,7 @@ void QDeclarativeListViewPrivate::layout() { Q_Q(QDeclarativeListView); layoutScheduled = false; - if (!isValid()) { + if (!isValid() && !visibleItems.count()) { clear(); setPosition(0); return; @@ -1043,6 +1049,8 @@ void QDeclarativeListViewPrivate::updateFooter() QDeclarative_setParent_noEvent(item, q->viewport()); item->setParentItem(q->viewport()); item->setZValue(1); + QDeclarativeItemPrivate *itemPrivate = static_cast<QDeclarativeItemPrivate*>(QGraphicsItemPrivate::get(item)); + itemPrivate->addItemChangeListener(this, QDeclarativeItemPrivate::Geometry); footer = new FxListItem(item, q); } } @@ -1081,6 +1089,8 @@ void QDeclarativeListViewPrivate::updateHeader() QDeclarative_setParent_noEvent(item, q->viewport()); item->setParentItem(q->viewport()); item->setZValue(1); + QDeclarativeItemPrivate *itemPrivate = static_cast<QDeclarativeItemPrivate*>(QGraphicsItemPrivate::get(item)); + itemPrivate->addItemChangeListener(this, QDeclarativeItemPrivate::Geometry); header = new FxListItem(item, q); if (visibleItems.isEmpty()) visiblePos = header->size(); @@ -1103,7 +1113,9 @@ void QDeclarativeListViewPrivate::updateHeader() void QDeclarativeListViewPrivate::fixupPosition() { - moveReason = Other; + if ((haveHighlightRange && highlightRange == QDeclarativeListView::StrictlyEnforceRange) + || snapMode != QDeclarativeListView::NoSnap) + moveReason = Other; if (orient == QDeclarativeListView::Vertical) fixupY(); else @@ -1112,7 +1124,6 @@ void QDeclarativeListViewPrivate::fixupPosition() void QDeclarativeListViewPrivate::fixup(AxisData &data, qreal minExtent, qreal maxExtent) { - Q_Q(QDeclarativeListView); if ((orient == QDeclarativeListView::Horizontal && &data == &vData) || (orient == QDeclarativeListView::Vertical && &data == &hData)) return; @@ -1120,7 +1131,41 @@ void QDeclarativeListViewPrivate::fixup(AxisData &data, qreal minExtent, qreal m int oldDuration = fixupDuration; fixupDuration = moveReason == Mouse ? fixupDuration : 0; - if (haveHighlightRange && highlightRange == QDeclarativeListView::StrictlyEnforceRange) { + if (snapMode != QDeclarativeListView::NoSnap) { + FxListItem *topItem = snapItemAt(position()+highlightRangeStart); + FxListItem *bottomItem = snapItemAt(position()+highlightRangeEnd); + qreal pos; + if (topItem && bottomItem && haveHighlightRange && highlightRange == QDeclarativeListView::StrictlyEnforceRange) { + qreal topPos = qMin(topItem->position() - highlightRangeStart, -maxExtent); + qreal bottomPos = qMax(bottomItem->position() - highlightRangeEnd, -minExtent); + pos = qAbs(data.move + topPos) < qAbs(data.move + bottomPos) ? topPos : bottomPos; + } else if (topItem) { + pos = qMax(qMin(topItem->position() - highlightRangeStart, -maxExtent), -minExtent); + } else if (bottomItem) { + pos = qMax(qMin(bottomItem->position() - highlightRangeStart, -maxExtent), -minExtent); + } else { + fixupDuration = oldDuration; + return; + } + if (currentItem && haveHighlightRange && highlightRange == QDeclarativeListView::StrictlyEnforceRange) { + updateHighlight(); + qreal currPos = currentItem->position(); + if (pos < currPos + currentItem->size() - highlightRangeEnd) + pos = currPos + currentItem->size() - highlightRangeEnd; + if (pos > currPos - highlightRangeStart) + pos = currPos - highlightRangeStart; + } + + qreal dist = qAbs(data.move + pos); + if (dist > 0) { + timeline.reset(data.move); + if (fixupDuration) + timeline.move(data.move, -pos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration/2); + else + timeline.set(data.move, -pos); + vTime = timeline.time(); + } + } else if (haveHighlightRange && highlightRange == QDeclarativeListView::StrictlyEnforceRange) { if (currentItem) { updateHighlight(); qreal pos = currentItem->position(); @@ -1132,30 +1177,13 @@ void QDeclarativeListViewPrivate::fixup(AxisData &data, qreal minExtent, qreal m timeline.reset(data.move); if (viewPos != position()) { - if (fixupDuration) { + if (fixupDuration) timeline.move(data.move, -viewPos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration/2); - } else { - data.move.setValue(-viewPos); - q->viewportMoved(); - } + else + timeline.set(data.move, -viewPos); } vTime = timeline.time(); } - } else if (snapMode != QDeclarativeListView::NoSnap) { - if (FxListItem *item = snapItemAt(position())) { - qreal pos = qMin(item->position() - highlightRangeStart, -maxExtent); - qreal dist = qAbs(data.move + pos); - if (dist > 0) { - timeline.reset(data.move); - if (fixupDuration) { - timeline.move(data.move, -pos, QEasingCurve(QEasingCurve::InOutQuad), fixupDuration/2); - } else { - data.move.setValue(-pos); - q->viewportMoved(); - } - vTime = timeline.time(); - } - } } else { QDeclarativeFlickablePrivate::fixup(data, minExtent, maxExtent); } @@ -1325,13 +1353,11 @@ void QDeclarativeListViewPrivate::flick(AxisData &data, qreal minExtent, qreal m Another component can display this model data in a ListView, like this: - \table - \row - \o \snippet doc/src/snippets/declarative/listview/listview.qml import + \snippet doc/src/snippets/declarative/listview/listview.qml import \codeline \snippet doc/src/snippets/declarative/listview/listview.qml classdocs simple - \o \image listview-simple.png - \endtable + + \image listview-simple.png Here, the ListView creates a \c ContactModel component for its model, and a \l Text element for its delegate. The view will create a new \l Text component for each item in the model. Notice @@ -1342,19 +1368,18 @@ void QDeclarativeListViewPrivate::flick(AxisData &data, qreal minExtent, qreal m with a blue \l Rectangle using the \l highlight property, and \c focus is set to \c true to enable keyboard navigation for the list view. - \table - \row - \o \snippet doc/src/snippets/declarative/listview/listview.qml classdocs advanced - \o \image listview-highlight.png - \endtable + \snippet doc/src/snippets/declarative/listview/listview.qml classdocs advanced + \image listview-highlight.png - In a ListView, delegates are instantiated as needed and may be destroyed at any time. + In a GridView, delegates are instantiated as needed and may be destroyed at any time. State should \e never be stored in a delegate. \note Views do not enable \e clip automatically. If the view is not clipped by another item or the screen, it will be necessary to set \e {clip: true} in order to have the out of view items clipped nicely. + + \sa ListModel, GridView */ QDeclarativeListView::QDeclarativeListView(QDeclarativeItem *parent) @@ -1466,13 +1491,15 @@ void QDeclarativeListView::setModel(const QVariant &model) disconnect(d->model, SIGNAL(destroyingItem(QDeclarativeItem*)), this, SLOT(destroyingItem(QDeclarativeItem*))); } d->clear(); + QDeclarativeVisualModel *oldModel = d->model; + d->model = 0; d->setPosition(0); d->modelVariant = model; QObject *object = qvariant_cast<QObject*>(model); QDeclarativeVisualModel *vim = 0; if (object && (vim = qobject_cast<QDeclarativeVisualModel *>(object))) { if (d->ownModel) { - delete d->model; + delete oldModel; d->ownModel = false; } d->model = vim; @@ -1480,6 +1507,8 @@ void QDeclarativeListView::setModel(const QVariant &model) if (!d->ownModel) { d->model = new QDeclarativeVisualDataModel(qmlContext(this), this); d->ownModel = true; + } else { + d->model = oldModel; } if (QDeclarativeVisualDataModel *dataModel = qobject_cast<QDeclarativeVisualDataModel*>(d->model)) dataModel->setModel(model); @@ -1630,7 +1659,7 @@ int QDeclarativeListView::count() const This property holds the component to use as the highlight. An instance of the highlight component is created for each list. - The geometry of the resultant component instance is managed by the list + The geometry of the resulting component instance is managed by the list so as to stay with the current item, unless the highlightFollowsCurrentItem property is false. @@ -1663,7 +1692,7 @@ void QDeclarativeListView::setHighlight(QDeclarativeComponent *highlight) highlight is not moved by the view, and any movement must be implemented by the highlight. - Here is a highlight with its motion defined by the a \l {SpringFollow} item: + Here is a highlight with its motion defined by a \l {SpringFollow} item: \snippet doc/src/snippets/declarative/listview/listview.qml highlightFollowsCurrentItem @@ -2038,8 +2067,8 @@ void QDeclarativeListView::setHighlightResizeDuration(int duration) /*! \qmlproperty enumeration ListView::snapMode - This property determines where the view's scrolling behavior stops following a drag or flick. - The allowed values are: + This property determines how the view scrolling will settle following a drag or flick. + The possible values are: \list \o ListView.NoSnap (default) - the view stops anywhere within the visible area. @@ -2071,6 +2100,15 @@ void QDeclarativeListView::setSnapMode(SnapMode mode) } } +/*! + \qmlproperty Component ListView::footer + This property holds the component to use as the footer. + + An instance of the footer component is created for each view. The + footer is positioned at the end of the view, after any items. + + \sa header +*/ QDeclarativeComponent *QDeclarativeListView::footer() const { Q_D(const QDeclarativeListView); @@ -2094,6 +2132,15 @@ void QDeclarativeListView::setFooter(QDeclarativeComponent *footer) } } +/*! + \qmlproperty Component ListView::header + This property holds the component to use as the header. + + An instance of the header component is created for each view. The + header is positioned at the beginning of the view, before any items. + + \sa footer +*/ QDeclarativeComponent *QDeclarativeListView::header() const { Q_D(const QDeclarativeListView); @@ -2219,7 +2266,9 @@ qreal QDeclarativeListView::maxYExtent() const if (d->orient == QDeclarativeListView::Horizontal) return height(); if (d->maxExtentDirty) { - if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) { + if (!d->model || !d->model->count()) { + d->maxExtent = 0; + } else if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) { d->maxExtent = -(d->positionAt(d->model->count()-1) - d->highlightRangeStart); if (d->highlightRangeEnd != d->highlightRangeStart) d->maxExtent = qMin(d->maxExtent, -(d->endPosition() - d->highlightRangeEnd + 1)); @@ -2261,7 +2310,9 @@ qreal QDeclarativeListView::maxXExtent() const if (d->orient == QDeclarativeListView::Vertical) return width(); if (d->maxExtentDirty) { - if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) { + if (!d->model || !d->model->count()) { + d->maxExtent = 0; + } else if (d->haveHighlightRange && d->highlightRange == StrictlyEnforceRange) { d->maxExtent = -(d->positionAt(d->model->count()-1) - d->highlightRangeStart); if (d->highlightRangeEnd != d->highlightRangeStart) d->maxExtent = qMin(d->maxExtent, -(d->endPosition() - d->highlightRangeEnd + 1)); diff --git a/src/declarative/graphicsitems/qdeclarativeloader.cpp b/src/declarative/graphicsitems/qdeclarativeloader.cpp index 4995baf..25b1119 100644 --- a/src/declarative/graphicsitems/qdeclarativeloader.cpp +++ b/src/declarative/graphicsitems/qdeclarativeloader.cpp @@ -112,30 +112,48 @@ void QDeclarativeLoaderPrivate::initResize() \inherits Item \brief The Loader item allows dynamically loading an Item-based - subtree from a QML URL or Component. + subtree from a URL or Component. - Loader instantiates an item from a component. The component to - instantiate may be specified directly by the \c sourceComponent - property, or loaded from a URL via the \c source property. + The Loader element instantiates an item from a component. The component to + be instantiated may be specified directly by the \l sourceComponent + property, or loaded from a URL via the \l source property. + + Loader can be used to delay the creation of a component until it is required. + For example, this loads "Page1.qml" as a component into the \l Loader element + when the \l MouseArea is clicked: - It is also an effective means of delaying the creation of a component - until it is required: \code - Loader { id: pageLoader } - Rectangle { - MouseArea { anchors.fill: parent; onClicked: pageLoader.source = "Page1.qml" } + import Qt 4.7 + + Item { + width: 200; height: 200 + + MouseArea { + anchors.fill: parent + onClicked: pageLoader.source = "Page1.qml" + } + + Loader { id: pageLoader } } \endcode + Note that Loader is like any other graphical Item and needs to be positioned + and sized accordingly to become visible. When a component is loaded, the + Loader is automatically resized to the size of the component. + If the Loader source is changed, any previous items instantiated - will be destroyed. Setting \c source to an empty string, or setting + will be destroyed. Setting \l source to an empty string, or setting sourceComponent to \e undefined will destroy the currently instantiated items, freeing resources and leaving the Loader empty. For example: \code pageLoader.source = "" + \endcode + or + + \code pageLoader.sourceComponent = undefined \endcode @@ -215,7 +233,7 @@ void QDeclarativeLoader::setSource(const QUrl &url) /*! \qmlproperty Component Loader::sourceComponent - The sourceComponent property holds the \l{Component} to instantiate. + This property holds the \l{Component} to instantiate. \qml Item { @@ -229,6 +247,8 @@ void QDeclarativeLoader::setSource(const QUrl &url) } \endqml + Note this value must hold a \l Component object; it cannot be a \l Item. + \sa source, progress */ @@ -340,19 +360,31 @@ void QDeclarativeLoaderPrivate::_q_sourceLoaded() \o Loader.Error - an error occurred while loading the QML source \endlist - Note that a change in the status property does not cause anything to happen - (although it reflects what has happened to the loader internally). If you wish - to react to the change in status you need to do it yourself, for example in one - of the following ways: - \list - \o Create a state, so that a state change occurs, e.g. State{name: 'loaded'; when: loader.status = Loader.Ready;} - \o Do something inside the onLoaded signal handler, e.g. Loader{id: loader; onLoaded: console.log('Loaded');} - \o Bind to the status variable somewhere, e.g. Text{text: if(loader.status!=Loader.Ready){'Not Loaded';}else{'Loaded';}} - \endlist - \sa progress + Use this status to provide an update or respond to the status change in some way. + For example, you could: + + \e {Trigger a state change:} + \qml + State { name: 'loaded'; when: loader.status = Loader.Ready } + \endqml + + \e {Implement an \c onStatusChanged signal handler:} + \qml + Loader { + id: loader + onStatusChanged: if (loader.status == Loader.Ready) console.log('Loaded') + } + \endqml + + \e {Bind to the status value:} + \qml + Text { text: loader.status != Loader.Ready ? 'Not Loaded' : 'Loaded' } + \endqml Note that if the source is a local file, the status will initially be Ready (or Error). While there will be no onStatusChanged signal in that case, the onLoaded will still be invoked. + + \sa progress */ QDeclarativeLoader::Status QDeclarativeLoader::status() const @@ -379,7 +411,7 @@ void QDeclarativeLoader::componentComplete() /*! \qmlsignal Loader::onLoaded() - This handler is called when the \l status becomes Loader.Ready, or on successful + This handler is called when the \l status becomes \c Loader.Ready, or on successful initial load. */ diff --git a/src/declarative/graphicsitems/qdeclarativemousearea.cpp b/src/declarative/graphicsitems/qdeclarativemousearea.cpp index 1947c00..c4956df 100644 --- a/src/declarative/graphicsitems/qdeclarativemousearea.cpp +++ b/src/declarative/graphicsitems/qdeclarativemousearea.cpp @@ -172,17 +172,21 @@ QDeclarativeMouseAreaPrivate::~QDeclarativeMouseAreaPrivate() A MouseArea is typically used in conjunction with a visible item, where the MouseArea effectively 'proxies' mouse handling for that - item. For example, we can put a MouseArea in a Rectangle that changes - the Rectangle color to red when clicked: - \snippet doc/src/snippets/declarative/mouseregion.qml 0 + item. For example, we can put a MouseArea in a \l Rectangle that changes + the \l Rectangle color to red when clicked: + + \snippet doc/src/snippets/declarative/mousearea.qml import + \codeline + \snippet doc/src/snippets/declarative/mousearea.qml intro Many MouseArea signals pass a \l {MouseEvent}{mouse} parameter that contains additional information about the mouse event, such as the position, button, and any key modifiers. - Below we have the previous - example extended so as to give a different color when you right click. - \snippet doc/src/snippets/declarative/mouseregion.qml 1 + Here is an extension of the previous example that produces a different + color when the area is right clicked: + + \snippet doc/src/snippets/declarative/mousearea.qml intro-extended For basic key handling, see the \l {Keys}{Keys attached property}. @@ -238,7 +242,7 @@ QDeclarativeMouseAreaPrivate::~QDeclarativeMouseAreaPrivate() releasing is also considered a click). The \l {MouseEvent}{mouse} parameter provides information about the click, including the x and y - position of the release of the click, and whether the click wasHeld. + position of the release of the click, and whether the click was held. The \e accepted property of the MouseEvent parameter is ignored in this handler. */ @@ -262,7 +266,7 @@ QDeclarativeMouseAreaPrivate::~QDeclarativeMouseAreaPrivate() This handler is called when there is a release. The \l {MouseEvent}{mouse} parameter provides information about the click, including the x and y - position of the release of the click, and whether the click wasHeld. + position of the release of the click, and whether the click was held. The \e accepted property of the MouseEvent parameter is ignored in this handler. */ @@ -282,7 +286,7 @@ QDeclarativeMouseAreaPrivate::~QDeclarativeMouseAreaPrivate() This handler is called when there is a double-click (a press followed by a release followed by a press). The \l {MouseEvent}{mouse} parameter provides information about the click, including the x and y - position of the release of the click, and whether the click wasHeld. + position of the release of the click, and whether the click was held. The \e accepted property of the MouseEvent parameter is ignored in this handler. */ @@ -301,12 +305,12 @@ QDeclarativeMouseAreaPrivate::~QDeclarativeMouseAreaPrivate() /*! \internal \class QDeclarativeMouseArea - \brief The QDeclarativeMouseArea class provides a simple mouse handling abstraction for use within Qml. + \brief The QDeclarativeMouseArea class provides a simple mouse handling abstraction for use within QML. All QDeclarativeItem derived classes can do mouse handling but the QDeclarativeMouseArea class exposes mouse handling data as properties and tracks flicking and dragging of the mouse. - A QDeclarativeMouseArea object can be instantiated in Qml using the tag \l MouseArea. + A QDeclarativeMouseArea object can be instantiated in QML using the tag \l MouseArea. */ QDeclarativeMouseArea::QDeclarativeMouseArea(QDeclarativeItem *parent) : QDeclarativeItem(*(new QDeclarativeMouseAreaPrivate), parent) @@ -328,10 +332,10 @@ QDeclarativeMouseArea::~QDeclarativeMouseArea() while a button is pressed, and will remain valid as long as the button is held even if the mouse is moved outside the area. - If hoverEnabled is true then these properties will be valid: + If hoverEnabled is true then these properties will be valid when: \list - \i when no button is pressed, but the mouse is within the MouseArea (containsMouse is true). - \i if a button is pressed and held, even if it has since moved out of the area. + \i no button is pressed, but the mouse is within the MouseArea (containsMouse is true). + \i a button is pressed and held, even if it has since moved out of the area. \endlist The coordinates are relative to the MouseArea. @@ -378,18 +382,7 @@ void QDeclarativeMouseArea::setEnabled(bool a) \endlist The code below displays "right" when the right mouse buttons is pressed: - \code - Text { - text: mr.pressedButtons & Qt.RightButton ? "right" : "" - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - MouseArea { - id: mr - acceptedButtons: Qt.LeftButton | Qt.RightButton - anchors.fill: parent - } - } - \endcode + \snippet doc/src/snippets/declarative/mousearea.qml mousebuttons \sa acceptedButtons */ @@ -417,7 +410,7 @@ void QDeclarativeMouseArea::mousePressEvent(QGraphicsSceneMouseEvent *event) setHovered(true); d->startScene = event->scenePos(); // we should only start timer if pressAndHold is connected to. - if (d->isConnected("pressAndHold(QDeclarativeMouseEvent*)")) + if (d->isPressAndHoldConnected()) d->pressAndHoldTimer.start(PressAndHoldDelay, this); setKeepMouseGrab(false); event->setAccepted(setPressed(true)); @@ -705,7 +698,7 @@ void QDeclarativeMouseArea::setHovered(bool h) MouseArea { acceptedButtons: Qt.LeftButton | Qt.RightButton } \endcode - The default is to accept the Left button. + The default value is \c Qt.LeftButton. */ Qt::MouseButtons QDeclarativeMouseArea::acceptedButtons() const { @@ -765,17 +758,19 @@ QDeclarativeDrag *QDeclarativeMouseArea::drag() \qmlproperty real MouseArea::drag.minimumY \qmlproperty real MouseArea::drag.maximumY - drag provides a convenient way to make an item draggable. + \c drag provides a convenient way to make an item draggable. \list - \i \c target specifies the item to drag. - \i \c active specifies if the target item is being currently dragged. - \i \c axis specifies whether dragging can be done horizontally (Drag.XAxis), vertically (Drag.YAxis), or both (Drag.XandYAxis) - \i the minimum and maximum properties limit how far the target can be dragged along the corresponding axes. + \i \c drag.target specifies the item to drag. + \i \c drag.active specifies if the target item is currently being dragged. + \i \c drag.axis specifies whether dragging can be done horizontally (\c Drag.XAxis), vertically (\c Drag.YAxis), or both (\c Drag.XandYAxis) + \i \c drag.minimum and \c drag.maximum limit how far the target can be dragged along the corresponding axes. \endlist - The following example uses drag to reduce the opacity of an image as it moves to the right: - \snippet doc/src/snippets/declarative/drag.qml 0 + The following example displays an image that can be dragged along the X-axis. The opacity + of the image is reduced when it is dragged to the right. + + \snippet doc/src/snippets/declarative/mousearea.qml drag */ QT_END_NAMESPACE diff --git a/src/declarative/graphicsitems/qdeclarativemousearea_p_p.h b/src/declarative/graphicsitems/qdeclarativemousearea_p_p.h index 4e909ff..3d7bd1e 100644 --- a/src/declarative/graphicsitems/qdeclarativemousearea_p_p.h +++ b/src/declarative/graphicsitems/qdeclarativemousearea_p_p.h @@ -88,9 +88,9 @@ public: lastModifiers = event->modifiers(); } - bool isConnected(const char *signal) { + bool isPressAndHoldConnected() { Q_Q(QDeclarativeMouseArea); - int idx = QObjectPrivate::get(q)->signalIndex(signal); + static int idx = QObjectPrivate::get(q)->signalIndex("pressAndHold(QDeclarativeMouseEvent*)"); return QObjectPrivate::get(q)->isSignalConnected(idx); } diff --git a/src/declarative/graphicsitems/qdeclarativepath.cpp b/src/declarative/graphicsitems/qdeclarativepath.cpp index 141a938..a904869 100644 --- a/src/declarative/graphicsitems/qdeclarativepath.cpp +++ b/src/declarative/graphicsitems/qdeclarativepath.cpp @@ -628,7 +628,7 @@ void QDeclarativePathLine::addToPath(QPainterPath &path) \qml Path { startX: 0; startY: 0 - PathQuad x: 200; y: 0; controlX: 100; controlY: 150 } + PathQuad { x: 200; y: 0; controlX: 100; controlY: 150 } } \endqml \endtable @@ -713,8 +713,9 @@ void QDeclarativePathQuad::addToPath(QPainterPath &path) Path { startX: 20; startY: 0 PathCubic { - x: 180; y: 0; control1X: -10; control1Y: 90 - control2X: 210; control2Y: 90 + x: 180; y: 0 + control1X: -10; control1Y: 90 + control2X: 210; control2Y: 90 } } \endqml diff --git a/src/declarative/graphicsitems/qdeclarativepathview.cpp b/src/declarative/graphicsitems/qdeclarativepathview.cpp index 448ec06..0c2d249 100644 --- a/src/declarative/graphicsitems/qdeclarativepathview.cpp +++ b/src/declarative/graphicsitems/qdeclarativepathview.cpp @@ -310,11 +310,21 @@ void QDeclarativePathViewPrivate::regenerate() \brief The PathView element lays out model-provided items on a path. \inherits Item - The model is typically provided by a QAbstractListModel "C++ model object", but can also be created directly in QML. + A PathView displays data from models created from built-in QML elements like ListModel + and XmlListModel, or custom model classes defined in C++ that inherit from + QAbstractListModel. + A ListView has a \l model, which defines the data to be displayed, and + a \l delegate, which defines how the data should be displayed. The \l delegate is instantiated for each item on the \l path. The items may be flicked to move them along the path. + For example, if there is a simple list model defined in a file \c ContactModel.qml like this: + + \snippet doc/src/snippets/declarative/pathview/ContactModel.qml 0 + + This data can be represented as a PathView, like this: + \snippet doc/src/snippets/declarative/pathview/pathview.qml 0 \image pathview.gif @@ -348,6 +358,13 @@ QDeclarativePathView::~QDeclarativePathView() } /*! + \qmlattachedproperty PathView PathView::view + This attached property holds the view that manages this delegate instance. + + It is attached to each instance of the delegate. +*/ + +/*! \qmlattachedproperty bool PathView::onPath This attached property holds whether the item is currently on the path. @@ -885,6 +902,7 @@ void QDeclarativePathView::setPathItemCount(int i) if (i < 1) i = 1; d->pathItems = i; + d->updateMappedRange(); if (d->isValid() && isComponentComplete()) { d->regenerate(); } diff --git a/src/declarative/graphicsitems/qdeclarativepositioners.cpp b/src/declarative/graphicsitems/qdeclarativepositioners.cpp index 8796e63..ad61bab 100644 --- a/src/declarative/graphicsitems/qdeclarativepositioners.cpp +++ b/src/declarative/graphicsitems/qdeclarativepositioners.cpp @@ -219,6 +219,7 @@ void QDeclarativeBasePositioner::prePositioning() QDeclarativeItem *child = qobject_cast<QDeclarativeItem *>(children.at(ii)); if (!child) continue; + QDeclarativeItemPrivate *childPrivate = static_cast<QDeclarativeItemPrivate*>(QGraphicsItemPrivate::get(child)); PositionedItem *item = 0; PositionedItem posItem(child); int wIdx = oldItems.find(posItem); @@ -227,11 +228,13 @@ void QDeclarativeBasePositioner::prePositioning() positionedItems.append(posItem); item = &positionedItems[positionedItems.count()-1]; item->isNew = true; - if (child->opacity() <= 0.0 || !child->isVisible()) + if (child->opacity() <= 0.0 || childPrivate->explicitlyHidden) item->isVisible = false; } else { item = &oldItems[wIdx]; - if (child->opacity() <= 0.0 || !child->isVisible()) { + // Items are only omitted from positioning if they are explicitly hidden + // i.e. their positioning is not affected if an ancestor is hidden. + if (child->opacity() <= 0.0 || childPrivate->explicitlyHidden) { item->isVisible = false; } else if (!item->isVisible) { item->isVisible = true; @@ -299,10 +302,16 @@ void QDeclarativeBasePositioner::finishApplyTransitions() d->moveActions.clear(); } +static inline bool isInvisible(QDeclarativeItem *child) +{ + QDeclarativeItemPrivate *childPrivate = static_cast<QDeclarativeItemPrivate*>(QGraphicsItemPrivate::get(child)); + return child->opacity() == 0.0 || childPrivate->explicitlyHidden || !child->width() || !child->height(); +} + /*! \qmlclass Column QDeclarativeColumn \since 4.7 - \brief The Column item lines up its children vertically. + \brief The Column item arranges its children vertically. \inherits Item The Column item positions its child items so that they are vertically @@ -346,8 +355,10 @@ Column { will not change. If you manually change the x or y properties in script, bind the x or y properties, use anchors on a child of a positioner, or have the height of a child depend on the position of a child, then the - positioner may exhibit strange behaviour. + positioner may exhibit strange behaviour. If you need to perform any of these + actions, consider positioning the items without the use of a Column. + \sa Row, {declarative/positioners}{Positioners example} */ /*! \qmlproperty Transition Column::add @@ -396,7 +407,7 @@ Column { spacing is the amount in pixels left empty between each adjacent item, and defaults to 0. - The below example places a Grid containing a red, a blue and a + The below example places a \l Grid containing a red, a blue and a green rectangle on a gray background. The area the grid positioner occupies is colored white. The top positioner has the default of no spacing, and the bottom positioner has its spacing set to 2. @@ -415,11 +426,6 @@ QDeclarativeColumn::QDeclarativeColumn(QDeclarativeItem *parent) { } -static inline bool isInvisible(QDeclarativeItem *child) -{ - return child->opacity() == 0.0 || !child->isVisible() || !child->width() || !child->height(); -} - void QDeclarativeColumn::doPositioning(QSizeF *contentSize) { int voffset = 0; @@ -468,17 +474,15 @@ void QDeclarativeColumn::reportConflictingAnchors() /*! \qmlclass Row QDeclarativeRow \since 4.7 - \brief The Row item lines up its children horizontally. + \brief The Row item arranges its children horizontally. \inherits Item The Row item positions its child items so that they are - horizontally aligned and not overlapping. Spacing can be added between the - items, and a margin around all items can also be added. It also provides for - transitions to be set when items are added, moved, or removed in the - positioner. Adding and removing apply both to items which are deleted or have - their position in the document changed so as to no longer be children of the - positioner, as well as to items which have their opacity set to or from zero - so as to appear or disappear. + horizontally aligned and not overlapping. + + Use \l spacing to set the spacing between items in a Row, and use the + \l add and \l move properties to set the transitions that should be applied + when items are added to, removed from, or re-positioned within the Row. The below example lays out differently shaped rectangles using a Row. \qml @@ -495,8 +499,10 @@ Row { will not change. If you manually change the x or y properties in script, bind the x or y properties, use anchors on a child of a positioner, or have the width of a child depend on the position of a child, then the - positioner may exhibit strange behaviour. + positioner may exhibit strange behaviour. If you need to perform any of these + actions, consider positioning the items without the use of a Row. + \sa Column, {declarative/positioners}{Positioners example} */ /*! \qmlproperty Transition Row::add @@ -504,12 +510,10 @@ Row { The transition will only be applied to the added item(s). Positioner transitions will only affect the position (x,y) of items. - Added can mean that either the object has been created or - reparented, and thus is now a child or the positioner, or that the + An object is considered to be added to the positioner if it has been + created or reparented and thus is now a child or the positioner, or if the object has had its opacity increased from zero, and thus is now visible. - - */ /*! \qmlproperty Transition Row::move @@ -540,7 +544,7 @@ Row { spacing is the amount in pixels left empty between each adjacent item, and defaults to 0. - The below example places a Grid containing a red, a blue and a + The below example places a \l Grid containing a red, a blue and a green rectangle on a gray background. The area the grid positioner occupies is colored white. The top positioner has the default of no spacing, and the bottom positioner has its spacing set to 2. @@ -610,18 +614,20 @@ void QDeclarativeRow::reportConflictingAnchors() \inherits Item The Grid item positions its child items so that they are - aligned in a grid and are not overlapping. Spacing can be added - between the items. It also provides for transitions to be set when items are + aligned in a grid and are not overlapping. + + Spacing can be added + between child items. It also provides for transitions to be set when items are added, moved, or removed in the positioner. Adding and removing apply both to items which are deleted or have their position in the document changed so as to no longer be children of the positioner, as well as to items which have their opacity set to or from zero so as to appear or disappear. - The Grid defaults to using four columns, and as many rows as - are necessary to fit all the child items. The number of rows - and/or the number of columns can be constrained by setting the rows - or columns properties. The grid positioner calculates a grid with + A Grid defaults to four columns, and as many rows as + are necessary to fit all child items. The number of rows + and/or the number of columns can be constrained by setting the \l rows + or \l columns properties. The grid positioner calculates a grid with rectangular cells of sufficient size to hold all items, and then places the items in the cells, going across then down, and positioning each item at the (0,0) corner of the cell. The below @@ -648,7 +654,10 @@ Grid { will not change. If you manually change the x or y properties in script, bind the x or y properties, use anchors on a child of a positioner, or have the width or height of a child depend on the position of a child, then the - positioner may exhibit strange behaviour. + positioner may exhibit strange behaviour. If you need to perform any of these + actions, consider positioning the items without the use of a Grid. + + \sa Flow, {declarative/positioners}{Positioners example} */ /*! \qmlproperty Transition Grid::add @@ -658,12 +667,10 @@ Grid { as that is all the positioners affect. To animate other property change you will have to do so based on how you have changed those properties. - Added can mean that either the object has been created or - reparented, and thus is now a child or the positioner, or that the + An object is considered to be added to the positioner if it has been + created or reparented and thus is now a child or the positioner, or if the object has had its opacity increased from zero, and thus is now visible. - - */ /*! \qmlproperty Transition Grid::move @@ -714,18 +721,16 @@ QDeclarativeGrid::QDeclarativeGrid(QDeclarativeItem *parent) : \qmlproperty int Grid::columns This property holds the number of columns in the grid. - When the columns property is set the Grid will always have - that many columns. Note that if you do not have enough items to - fill this many columns some columns will be of zero width. + If the grid does not have enough items to fill the specified + number of columns, some columns will be of zero width. */ /*! \qmlproperty int Grid::rows This property holds the number of rows in the grid. - When the rows property is set the Grid will always have that - many rows. Note that if you do not have enough items to fill this - many rows some rows will be of zero width. + If the grid does not have enough items to fill the specified + number of rows, some rows will be of zero width. */ void QDeclarativeGrid::setColumns(const int columns) @@ -750,12 +755,14 @@ void QDeclarativeGrid::setRows(const int rows) \qmlproperty enumeration Grid::flow This property holds the flow of the layout. - Possible values are \c Grid.LeftToRight (default) and \c Grid.TopToBottom. + Possible values are: - If \a flow is \c Grid.LeftToRight, the items are positioned next to - to each other from left to right, then wrapped to the next line. - If \a flow is \c Grid.TopToBottom, the items are positioned next to each - other from top to bottom, then wrapped to the next column. + \list + \o Grid.LeftToRight (default) - Items are positioned next to + to each other from left to right, then wrapped to the next line. + \o Grid.TopToBottom - Items are positioned next to each + other from top to bottom, then wrapped to the next column. + \endlist */ QDeclarativeGrid::Flow QDeclarativeGrid::flow() const { @@ -893,15 +900,20 @@ void QDeclarativeGrid::reportConflictingAnchors() /*! \qmlclass Flow QDeclarativeFlow \since 4.7 - \brief The Flow item lines up its children side by side, wrapping as necessary. + \brief The Flow item arranges its children side by side, wrapping as necessary. \inherits Item + The Flow item positions its child items so that they are side by side and are + not overlapping. + Note that the positioner assumes that the x and y positions of its children will not change. If you manually change the x or y properties in script, bind the x or y properties, use anchors on a child of a positioner, or have the width or height of a child depend on the position of a child, then the - positioner may exhibit strange behaviour. + positioner may exhibit strange behaviour. If you need to perform any of these + actions, consider positioning the items without the use of a Flow. + \sa Grid, {declarative/positioners}{Positioners example} */ /*! \qmlproperty Transition Flow::add @@ -909,9 +921,10 @@ void QDeclarativeGrid::reportConflictingAnchors() The transition will only be applied to the added item(s). Positioner transitions will only affect the position (x,y) of items. - Added can mean that either the object has been created or reparented, and thus is now a child or the positioner, or that the object has had its opacity increased from zero, and thus is now visible. - - + An object is considered to be added to the positioner if it has been + created or reparented and thus is now a child or the positioner, or if the + object has had its opacity increased from zero, and thus is now + visible. */ /*! \qmlproperty Transition Flow::move @@ -965,14 +978,16 @@ QDeclarativeFlow::QDeclarativeFlow(QDeclarativeItem *parent) \qmlproperty enumeration Flow::flow This property holds the flow of the layout. - Possible values are \c Flow.LeftToRight (default) and \c Flow.TopToBottom. + Possible values are: - If \a flow is \c Flow.LeftToRight, the items are positioned next to + \list + \o Flow.LeftToRight (default) - Items are positioned next to to each other from left to right until the width of the Flow is exceeded, then wrapped to the next line. - If \a flow is \c Flow.TopToBottom, the items are positioned next to each + \o Flow.TopToBottom - Items are positioned next to each other from top to bottom until the height of the Flow is exceeded, then wrapped to the next column. + \endlist */ QDeclarativeFlow::Flow QDeclarativeFlow::flow() const { diff --git a/src/declarative/graphicsitems/qdeclarativepositioners_p_p.h b/src/declarative/graphicsitems/qdeclarativepositioners_p_p.h index 04f0181..822079b 100644 --- a/src/declarative/graphicsitems/qdeclarativepositioners_p_p.h +++ b/src/declarative/graphicsitems/qdeclarativepositioners_p_p.h @@ -100,18 +100,23 @@ public: bool doingPositioning : 1; bool anchorConflict : 1; - virtual void itemSiblingOrderChanged(QDeclarativeItem* other) + void schedulePositioning() { Q_Q(QDeclarativeBasePositioner); - Q_UNUSED(other); if(!queuedPositioning){ - //Delay is due to many children often being reordered at once - //And we only want to reposition them all once QTimer::singleShot(0,q,SLOT(prePositioning())); queuedPositioning = true; } } + virtual void itemSiblingOrderChanged(QDeclarativeItem* other) + { + Q_UNUSED(other); + //Delay is due to many children often being reordered at once + //And we only want to reposition them all once + schedulePositioning(); + } + void itemGeometryChanged(QDeclarativeItem *, const QRectF &newGeometry, const QRectF &oldGeometry) { Q_Q(QDeclarativeBasePositioner); @@ -120,8 +125,7 @@ public: } virtual void itemVisibilityChanged(QDeclarativeItem *) { - Q_Q(QDeclarativeBasePositioner); - q->prePositioning(); + schedulePositioning(); } virtual void itemOpacityChanged(QDeclarativeItem *) { diff --git a/src/declarative/graphicsitems/qdeclarativerectangle.cpp b/src/declarative/graphicsitems/qdeclarativerectangle.cpp index 301ca00..2756877 100644 --- a/src/declarative/graphicsitems/qdeclarativerectangle.cpp +++ b/src/declarative/graphicsitems/qdeclarativerectangle.cpp @@ -160,6 +160,8 @@ void QDeclarativeGradient::doUpdate() You can also create rounded rectangles using the \l radius property. \qml + import Qt 4.7 + Rectangle { width: 100 height: 100 @@ -202,8 +204,20 @@ void QDeclarativeRectangle::doUpdate() A width of 1 creates a thin line. For no line, use a width of 0 or a transparent color. - To keep the border smooth (rather than blurry), odd widths cause the rectangle to be painted at - a half-pixel offset; + If \c border.width is an odd number, the rectangle is painted at a half-pixel offset to retain + border smoothness. Also, the border is rendered evenly on either side of the + rectangle's boundaries, and the spare pixel is rendered to the right and below the + rectangle (as documented for QRect rendering). This can cause unintended effects if + \c border.width is 1 and the rectangle is \l{Item::clip}{clipped} by a parent item: + + \table + \row + \o \snippet doc/src/snippets/declarative/rect-border-width.qml 0 + \o \image rect-border-width.png + \endtable + + Here, the innermost rectangle's border is clipped on the bottom and right edges by its + parent. To avoid this, the border width can be set to two instead of one. */ QDeclarativePen *QDeclarativeRectangle::border() { diff --git a/src/declarative/graphicsitems/qdeclarativerepeater.cpp b/src/declarative/graphicsitems/qdeclarativerepeater.cpp index 04076f8..995e22a 100644 --- a/src/declarative/graphicsitems/qdeclarativerepeater.cpp +++ b/src/declarative/graphicsitems/qdeclarativerepeater.cpp @@ -65,49 +65,75 @@ QDeclarativeRepeaterPrivate::~QDeclarativeRepeaterPrivate() \since 4.7 \inherits Item - \brief The Repeater item allows you to repeat an Item-based component using a model. + \brief The Repeater element allows you to repeat an Item-based component using a model. - The Repeater item is used to create a large number of - similar items. For each entry in the model, an item is instantiated - in a context seeded with data from the model. If the repeater will - be instantiating a large number of instances, it may be more efficient to - use one of Qt Declarative's \l {xmlViews}{view items}. + The Repeater element is used to create a large number of + similar items. Like other view elements, a Repeater has a \l model and a \l delegate: + for each entry in the model, the delegate is instantiated + in a context seeded with data from the model. A Repeater item is usually + enclosed in a positioner element such as \l Row or \l Column to visually + position the multiple delegate items created by the Repeater. - The model may be either an object list, a string list, a number or a Qt model. - In each case, the data element and the index is exposed to each instantiated - component. - - The index is always exposed as an accessible \c index property. - In the case of an object or string list, the data element (of type string - or object) is available as the \c modelData property. In the case of a Qt model, - all roles are available as named properties just like in the view classes. The - following example shows how to use the index property inside the instantiated - items. + The following Repeater creates three instances of a \l Rectangle item within + a \l Row: + + \snippet doc/src/snippets/declarative/repeater.qml import + \codeline + \snippet doc/src/snippets/declarative/repeater.qml simple + + \image repeater-simple.png + + The \l model of a Repeater can be specified as a model object, a number, a string list + or an object list. If a model object is used, the + \l delegate can access the model roles as named properties, just as for view elements like + ListView and GridView. + + The \l delegate can also access two additional properties: - \snippet doc/src/snippets/declarative/repeater-index.qml 0 + \list + \o \c index - the index of the delegate's item + \o \c modelData - the data element for the delegate, which is useful where the \l model is a string or object list + \endlist - \image repeater-index.png + Here is a Repeater that uses the \c index property inside the instantiated items: + + \table + \row + \o \snippet doc/src/snippets/declarative/repeater.qml index + \o \image repeater-index.png + \endtable + + Here is another Repeater that uses the \c modelData property to reference the data for a + particular index: + + \table + \row + \o \snippet doc/src/snippets/declarative/repeater.qml modeldata + \o \image repeater-modeldata.png + \endtable Items instantiated by the Repeater are inserted, in order, as children of the Repeater's parent. The insertion starts immediately after - the repeater's position in its parent stacking list. This is to allow - you to use a Repeater inside a layout. The following QML example shows how - the instantiated items would visually appear stacked between the red and - blue rectangles. - - \snippet doc/src/snippets/declarative/repeater.qml 0 + the repeater's position in its parent stacking list. This allows + a Repeater to be used inside a layout. For example, the following Repeater's + items are stacked between a red rectangle and a blue rectangle: + + \snippet doc/src/snippets/declarative/repeater.qml layout \image repeater.png - The repeater instance continues to own all items it instantiates, even - if they are otherwise manipulated. It is illegal to manually remove an item - created by the Repeater. + A Repeater item owns all items it instantiates. Removing or dynamically destroying + an item created by a Repeater results in unpredictable behavior. - \note Repeater is Item-based, and cannot be used to repeat non-Item-derived objects. + Note that if a repeater is + required to instantiate a large number of items, it may be more efficient to + use other view elements such as ListView. + + \note Repeater is \l {Item}-based, and can only repeat \l {Item}-derived objects. For example, it cannot be used to repeat QtObjects. \badcode Item { - //XXX illegal. Can't repeat QtObject as it doesn't derive from Item. + //XXX does not work! Can't repeat QtObject as it doesn't derive from Item. Repeater { model: 10 QtObject {} @@ -143,7 +169,15 @@ QDeclarativeRepeater::~QDeclarativeRepeater() The model providing data for the repeater. - The model may be either an object list, a string list, a number or a Qt model. + This property can be set to any of the following: + + \list + \o A number that indicates the number of delegates to be created + \o A model (e.g. a ListModel item, or a QAbstractItemModel subclass) + \o A string list + \o An object list + \endlist + In each case, the data element and the index is exposed to each instantiated component. The index is always exposed as an accessible \c index property. In the case of an object or string list, the data element (of type string diff --git a/src/declarative/graphicsitems/qdeclarativescalegrid.cpp b/src/declarative/graphicsitems/qdeclarativescalegrid.cpp index fe89190..a053aa0 100644 --- a/src/declarative/graphicsitems/qdeclarativescalegrid.cpp +++ b/src/declarative/graphicsitems/qdeclarativescalegrid.cpp @@ -130,8 +130,9 @@ QDeclarativeGridScaledImage::QDeclarativeGridScaledImage(QIODevice *data) int b = -1; QString imgFile; - while(!data->atEnd()) { - QString line = QString::fromUtf8(data->readLine().trimmed()); + QByteArray raw; + while(raw = data->readLine(), !raw.isEmpty()) { + QString line = QString::fromUtf8(raw.trimmed()); if (line.isEmpty() || line.startsWith(QLatin1Char('#'))) continue; diff --git a/src/declarative/graphicsitems/qdeclarativetext.cpp b/src/declarative/graphicsitems/qdeclarativetext.cpp index 55cef8b..c2e0d67 100644 --- a/src/declarative/graphicsitems/qdeclarativetext.cpp +++ b/src/declarative/graphicsitems/qdeclarativetext.cpp @@ -126,10 +126,10 @@ QSet<QUrl> QTextDocumentWithImageResources::errors; \image declarative-text.png If height and width are not explicitly set, Text will attempt to determine how - much room is needed and set it accordingly. Unless \c wrapMode is set, it will always + much room is needed and set it accordingly. Unless \l wrapMode is set, it will always prefer width to height (all text will be placed on a single line). - The \c elide property can alternatively be used to fit a single line of + The \l elide property can alternatively be used to fit a single line of plain text to a set width. Note that the \l{Supported HTML Subset} is limited. Also, if the text contains @@ -161,7 +161,7 @@ QSet<QUrl> QTextDocumentWithImageResources::errors; The \c elide property can alternatively be used to fit a line of plain text to a set width. - A QDeclarativeText object can be instantiated in Qml using the tag \c Text. + A QDeclarativeText object can be instantiated in QML using the tag \c Text. */ QDeclarativeText::QDeclarativeText(QDeclarativeItem *parent) : QDeclarativeItem(*(new QDeclarativeTextPrivate), parent) @@ -477,6 +477,7 @@ void QDeclarativeText::setHAlign(HAlignment align) return; d->hAlign = align; + update(); emit horizontalAlignmentChanged(align); } @@ -493,6 +494,7 @@ void QDeclarativeText::setVAlign(VAlignment align) return; d->vAlign = align; + update(); emit verticalAlignmentChanged(align); } @@ -503,13 +505,11 @@ void QDeclarativeText::setVAlign(VAlignment align) wrap if an explicit width has been set. wrapMode can be one of: \list - \o Text.NoWrap - no wrapping will be performed. If the text contains insufficient newlines, then implicitWidth will exceed a set width. - \o Text.WordWrap - wrapping is done on word boundaries only. If a word is too long, implicitWidth will exceed a set width. + \o Text.NoWrap (default) - no wrapping will be performed. If the text contains insufficient newlines, then \l paintedWidth will exceed a set width. + \o Text.WordWrap - wrapping is done on word boundaries only. If a word is too long, \l paintedWidth will exceed a set width. \o Text.WrapAnywhere - wrapping is done at any point on a line, even if it occurs in the middle of a word. \o Text.Wrap - if possible, wrapping occurs at a word boundary; otherwise it will occur at the appropriate point on the line, even in the middle of a word. \endlist - - The default is Text.NoWrap. */ QDeclarativeText::WrapMode QDeclarativeText::wrapMode() const { @@ -539,13 +539,13 @@ void QDeclarativeText::setWrapMode(WrapMode mode) Supported text formats are: \list - \o Text.AutoText + \o Text.AutoText (default) \o Text.PlainText \o Text.RichText \o Text.StyledText \endlist - The default is Text.AutoText. If the text format is Text.AutoText the text element + If the text format is \c Text.AutoText the text element will automatically determine whether the text should be treated as rich text. This determination is made using Qt::mightBeRichText(). @@ -1167,7 +1167,7 @@ void QDeclarativeText::mousePressEvent(QGraphicsSceneMouseEvent *event) } /*! - \qmlsignal Text::linkActivated(link) + \qmlsignal Text::onLinkActivated(link) This handler is called when the user clicks on a link embedded in the text. */ diff --git a/src/declarative/graphicsitems/qdeclarativetextedit.cpp b/src/declarative/graphicsitems/qdeclarativetextedit.cpp index 15cdb05..3b4f2a7 100644 --- a/src/declarative/graphicsitems/qdeclarativetextedit.cpp +++ b/src/declarative/graphicsitems/qdeclarativetextedit.cpp @@ -62,25 +62,28 @@ QT_BEGIN_NAMESPACE /*! \qmlclass TextEdit QDeclarativeTextEdit \since 4.7 - \brief The TextEdit item allows you to add editable formatted text to a scene. + \brief The TextEdit item displays multiple lines of editable formatted text. \inherits Item + The TextEdit item displays a block of editable, formatted text. + It can display both plain and rich text. For example: \qml TextEdit { - id: edit + width: 240 text: "<b>Hello</b> <i>World!</i>" - focus: true font.family: "Helvetica" font.pointSize: 20 color: "blue" - width: 240 + focus: true } \endqml \image declarative-textedit.gif + Setting \l {Item::focus}{focus} to \c true enables the TextEdit item to receive keyboard focus. + Note that the TextEdit does not implement scrolling, following the cursor, or other behaviors specific to a look-and-feel. For example, to add flickable scrolling that follows the cursor: @@ -96,7 +99,7 @@ TextEdit { You can translate between cursor positions (characters from the start of the document) and pixel points using positionAt() and positionToRectangle(). - \sa Text + \sa Text, TextInput */ /*! @@ -110,7 +113,7 @@ TextEdit { \image declarative-textedit.png - A QDeclarativeTextEdit object can be instantiated in Qml using the tag \c <TextEdit>. + A QDeclarativeTextEdit object can be instantiated in QML using the tag \c <TextEdit>. */ /*! @@ -206,7 +209,7 @@ QString QDeclarativeTextEdit::text() const Sets the font size in pixels. Using this function makes the font device dependent. - Use \c pointSize to set the size of the font in a device independent manner. + Use \l pointSize to set the size of the font in a device independent manner. */ /*! @@ -453,12 +456,22 @@ void QDeclarativeTextEdit::setSelectedTextColor(const QColor &color) \qmlproperty enumeration TextEdit::horizontalAlignment \qmlproperty enumeration TextEdit::verticalAlignment - Sets the horizontal and vertical alignment of the text within the TextEdit items + Sets the horizontal and vertical alignment of the text within the TextEdit item's width and height. By default, the text is top-left aligned. - The valid values for \c horizontalAlignment are \c TextEdit.AlignLeft, \c TextEdit.AlignRight and - \c TextEdit.AlignHCenter. The valid values for \c verticalAlignment are \c TextEdit.AlignTop, \c TextEdit.AlignBottom - and \c TextEdit.AlignVCenter. + Valid values for \c horizontalAlignment are: + \list + \o TextEdit.AlignLeft (default) + \o TextEdit.AlignRight + \o TextEdit.AlignHCenter + \endlist + + Valid values for \c verticalAlignment are: + \list + \o TextEdit.AlignTop (default) + \o TextEdit.AlignBottom + \c TextEdit.AlignVCenter + \endlist */ QDeclarativeTextEdit::HAlignment QDeclarativeTextEdit::hAlign() const { @@ -529,8 +542,8 @@ void QDeclarativeTextEdit::setWrapMode(WrapMode mode) /*! \qmlproperty real TextEdit::paintedWidth - Returns the width of the text, including width past the width - which is covered due to insufficient wrapping if WrapMode is set. + Returns the width of the text, including the width past the width + which is covered due to insufficient wrapping if \l wrapMode is set. */ qreal QDeclarativeTextEdit::paintedWidth() const { @@ -540,8 +553,8 @@ qreal QDeclarativeTextEdit::paintedWidth() const /*! \qmlproperty real TextEdit::paintedHeight - Returns the height of the text, including height past the height - which is covered due to there being more text than fits in the set height. + Returns the height of the text, including the height past the height + that is covered if the text does not fit within the set height. */ qreal QDeclarativeTextEdit::paintedHeight() const { @@ -567,10 +580,10 @@ QRectF QDeclarativeTextEdit::positionToRectangle(int pos) const /*! \qmlmethod int TextEdit::positionAt(x,y) - Returns the text position closest to pixel position (\a x,\a y). + Returns the text position closest to pixel position (\a x, \a y). Position 0 is before the first character, position 1 is after the first character - but before the second, and so on until position text.length, which is after all characters. + but before the second, and so on until position \l {text}.length, which is after all characters. */ int QDeclarativeTextEdit::positionAt(int x, int y) const { @@ -580,7 +593,7 @@ int QDeclarativeTextEdit::positionAt(int x, int y) const } /*! - \qmlmethod int TextEdit::moveCursorSeletion(int pos) + \qmlmethod int TextEdit::moveCursorSelection(int pos) Moves the cursor to \a position and updates the selection accordingly. (To only move the cursor, set the \l cursorPosition property.) @@ -727,12 +740,9 @@ void QDeclarativeTextEdit::loadCursorDelegate() \qmlproperty int TextEdit::selectionStart The cursor position before the first character in the current selection. - Setting this and selectionEnd allows you to specify a selection in the - text edit. - Note that if selectionStart == selectionEnd then there is no current - selection. If you attempt to set selectionStart to a value outside of - the current text, selectionStart will not be changed. + This property is read-only. To change the selection, use select(start,end), + selectAll(), or selectWord(). \sa selectionEnd, cursorPosition, selectedText */ @@ -742,25 +752,13 @@ int QDeclarativeTextEdit::selectionStart() const return d->control->textCursor().selectionStart(); } -void QDeclarativeTextEdit::setSelectionStart(int s) -{ - Q_D(QDeclarativeTextEdit); - if(d->lastSelectionStart == s || s < 0 || s > text().length()) - return; - d->lastSelectionStart = s; - d->updateSelection();// Will emit the relevant signals -} - /*! \qmlproperty int TextEdit::selectionEnd The cursor position after the last character in the current selection. - Setting this and selectionStart allows you to specify a selection in the - text edit. - Note that if selectionStart == selectionEnd then there is no current - selection. If you attempt to set selectionEnd to a value outside of - the current text, selectionEnd will not be changed. + This property is read-only. To change the selection, use select(start,end), + selectAll(), or selectWord(). \sa selectionStart, cursorPosition, selectedText */ @@ -770,15 +768,6 @@ int QDeclarativeTextEdit::selectionEnd() const return d->control->textCursor().selectionEnd(); } -void QDeclarativeTextEdit::setSelectionEnd(int s) -{ - Q_D(QDeclarativeTextEdit); - if(d->lastSelectionEnd == s || s < 0 || s > text().length()) - return; - d->lastSelectionEnd = s; - d->updateSelection();// Will emit the relevant signals -} - /*! \qmlproperty string TextEdit::selectedText @@ -1028,6 +1017,8 @@ void QDeclarativeTextEditPrivate::focusChanged(bool hasFocus) } /*! + \qmlmethod void TextEdit::selectAll() + Causes all text to be selected. */ void QDeclarativeTextEdit::selectAll() @@ -1037,6 +1028,8 @@ void QDeclarativeTextEdit::selectAll() } /*! + \qmlmethod void TextEdit::selectWord() + Causes the word closest to the current cursor position to be selected. */ void QDeclarativeTextEdit::selectWord() @@ -1048,6 +1041,36 @@ void QDeclarativeTextEdit::selectWord() } /*! + \qmlmethod void TextEdit::select(start,end) + + Causes the text from \a start to \a end to be selected. + + If either start or end is out of range, the selection is not changed. + + After calling this, selectionStart will become the lesser + and selectionEnd will become the greater (regardless of the order passed + to this method). + + \sa selectionStart, selectionEnd +*/ +void QDeclarativeTextEdit::select(int start, int end) +{ + Q_D(QDeclarativeTextEdit); + if (start < 0 || end < 0 || start > d->text.length() || end > d->text.length()) + return; + QTextCursor cursor = d->control->textCursor(); + cursor.beginEditBlock(); + cursor.setPosition(start, QTextCursor::MoveAnchor); + cursor.setPosition(end, QTextCursor::KeepAnchor); + cursor.endEditBlock(); + d->control->setTextCursor(cursor); + + // QTBUG-11100 + updateSelectionMarkers(); +} + +#ifndef QT_NO_CLIPBOARD +/*! \qmlmethod TextEdit::cut() Moves the currently selected text to the system clipboard. @@ -1072,14 +1095,14 @@ void QDeclarativeTextEdit::copy() /*! \qmlmethod TextEdit::paste() - Relaces the currently selected text by the contents of the system clipboard. + Replaces the currently selected text by the contents of the system clipboard. */ void QDeclarativeTextEdit::paste() { Q_D(QDeclarativeTextEdit); d->control->paste(); } - +#endif // QT_NO_CLIPBOARD /*! \overload @@ -1097,9 +1120,15 @@ void QDeclarativeTextEdit::mousePressEvent(QGraphicsSceneMouseEvent *event) p = p->parentItem(); } setFocus(true); - if (hasFocus() == hadFocus && d->showInputPanelOnFocus && !isReadOnly()) { - // re-open input panel on press if already focused - openSoftwareInputPanel(); + if (d->showInputPanelOnFocus) { + if (hasFocus() && hadFocus && !isReadOnly()) { + // re-open input panel on press if already focused + openSoftwareInputPanel(); + } + } else { // show input panel on click + if (hasFocus() && !hadFocus) { + d->clickCausedFocus = true; + } } } if (event->type() != QEvent::GraphicsSceneMouseDoubleClick || d->selectByMouse) @@ -1116,6 +1145,17 @@ void QDeclarativeTextEdit::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { Q_D(QDeclarativeTextEdit); d->control->processEvent(event, QPointF(0, -d->yoff)); + if (!d->showInputPanelOnFocus) { // input panel on click + if (d->focusOnPress && !isReadOnly() && boundingRect().contains(event->pos())) { + if (QGraphicsView * view = qobject_cast<QGraphicsView*>(qApp->focusWidget())) { + if (view->scene() && view->scene() == scene()) { + qt_widget_private(view)->handleSoftwareInputPanel(event->button(), d->clickCausedFocus); + } + } + } + } + d->clickCausedFocus = false; + if (!event->isAccepted()) QDeclarativePaintedItem::mouseReleaseEvent(event); } @@ -1192,9 +1232,14 @@ void QDeclarativeTextEdit::drawContents(QPainter *painter, const QRect &bounds) void QDeclarativeTextEdit::updateImgCache(const QRectF &rf) { Q_D(const QDeclarativeTextEdit); - QRect r = rf.toRect(); - if (r != QRect(0,0,INT_MAX,INT_MAX)) // Don't translate "everything" - r = r.translated(0,d->yoff); + QRect r; + if (!rf.isValid()) { + r = QRect(0,0,INT_MAX,INT_MAX); + } else { + r = rf.toRect(); + if (r != QRect(0,0,INT_MAX,INT_MAX)) // Don't translate "everything" + r = r.translated(0,d->yoff); + } dirtyCache(r); emit update(); } @@ -1264,7 +1309,6 @@ void QDeclarativeTextEditPrivate::updateSelection() QTextCursor cursor = control->textCursor(); bool startChange = (lastSelectionStart != cursor.selectionStart()); bool endChange = (lastSelectionEnd != cursor.selectionEnd()); - //### Is it worth calculating a more minimal set of movements? cursor.beginEditBlock(); cursor.setPosition(lastSelectionStart, QTextCursor::MoveAnchor); cursor.setPosition(lastSelectionEnd, QTextCursor::KeepAnchor); @@ -1274,8 +1318,6 @@ void QDeclarativeTextEditPrivate::updateSelection() q->selectionStartChanged(); if(endChange) q->selectionEndChanged(); - startChange = (lastSelectionStart != control->textCursor().selectionStart()); - endChange = (lastSelectionEnd != control->textCursor().selectionEnd()); } void QDeclarativeTextEdit::updateSelectionMarkers() @@ -1361,10 +1403,14 @@ void QDeclarativeTextEditPrivate::updateDefaultTextOption() customizing when you want the input keyboard to be shown and hidden in your application. - By default input panels are shown when TextEdit element gains focus and hidden - when the focus is lost. You can disable the automatic behavior by setting the - property showInputPanelOnFocus to false and use functions openSoftwareInputPanel() - and closeSoftwareInputPanel() to implement the behavior you want. + By default the opening of input panels follows the platform style. On Symbian^1 and + Symbian^3 -based devices the panels are opened by clicking TextEdit. On other platforms + the panels are automatically opened when TextEdit element gains focus. Input panels are + always closed if no editor owns focus. + + You can disable the automatic behavior by setting the property \c focusOnPress to false + and use functions openSoftwareInputPanel() and closeSoftwareInputPanel() to implement + the behavior you want. Only relevant on platforms, which provide virtual keyboards. @@ -1373,12 +1419,19 @@ void QDeclarativeTextEditPrivate::updateDefaultTextOption() TextEdit { id: textEdit text: "Hello world!" - showInputPanelOnFocus: false + focusOnPress: false MouseArea { anchors.fill: parent - onClicked: textEdit.openSoftwareInputPanel() + onClicked: { + if (!textEdit.focus) { + textEdit.focus = true; + textEdit.openSoftwareInputPanel(); + } else { + textEdit.focus = false; + } + } + onPressAndHold: textEdit.closeSoftwareInputPanel(); } - onFocusChanged: if (!focus) closeSoftwareInputpanel() } \endcode */ @@ -1401,10 +1454,14 @@ void QDeclarativeTextEdit::openSoftwareInputPanel() for customizing when you want the input keyboard to be shown and hidden in your application. - By default input panels are shown when TextEdit element gains focus and hidden - when the focus is lost. You can disable the automatic behavior by setting the - property showInputPanelOnFocus to false and use functions openSoftwareInputPanel() - and closeSoftwareInputPanel() to implement the behavior you want. + By default the opening of input panels follows the platform style. On Symbian^1 and + Symbian^3 -based devices the panels are opened by clicking TextEdit. On other platforms + the panels are automatically opened when TextEdit element gains focus. Input panels are + always closed if no editor owns focus. + + You can disable the automatic behavior by setting the property \c focusOnPress to false + and use functions openSoftwareInputPanel() and closeSoftwareInputPanel() to implement + the behavior you want. Only relevant on platforms, which provide virtual keyboards. @@ -1413,12 +1470,19 @@ void QDeclarativeTextEdit::openSoftwareInputPanel() TextEdit { id: textEdit text: "Hello world!" - showInputPanelOnFocus: false + focusOnPress: false MouseArea { anchors.fill: parent - onClicked: textEdit.openSoftwareInputPanel() + onClicked: { + if (!textEdit.focus) { + textEdit.focus = true; + textEdit.openSoftwareInputPanel(); + } else { + textEdit.focus = false; + } + } + onPressAndHold: textEdit.closeSoftwareInputPanel(); } - onFocusChanged: if (!focus) closeSoftwareInputpanel() } \endcode */ @@ -1434,46 +1498,15 @@ void QDeclarativeTextEdit::closeSoftwareInputPanel() } } -/*! - \qmlproperty bool TextEdit::showInputPanelOnFocus - Whether input panels are automatically shown when TextEdit element gains - focus and hidden when focus is lost. By default this is set to true. - - Only relevant on platforms, which provide virtual keyboards. -*/ -bool QDeclarativeTextEdit::showInputPanelOnFocus() const -{ - Q_D(const QDeclarativeTextEdit); - return d->showInputPanelOnFocus; -} - -void QDeclarativeTextEdit::setShowInputPanelOnFocus(bool showOnFocus) -{ - Q_D(QDeclarativeTextEdit); - if (d->showInputPanelOnFocus == showOnFocus) - return; - - d->showInputPanelOnFocus = showOnFocus; - - emit showInputPanelOnFocusChanged(d->showInputPanelOnFocus); -} - void QDeclarativeTextEdit::focusInEvent(QFocusEvent *event) { Q_D(const QDeclarativeTextEdit); - if (d->showInputPanelOnFocus && !isReadOnly() && event->reason() != Qt::ActiveWindowFocusReason) { - openSoftwareInputPanel(); + if (d->showInputPanelOnFocus) { + if (d->focusOnPress && !isReadOnly()) { + openSoftwareInputPanel(); + } } QDeclarativePaintedItem::focusInEvent(event); } -void QDeclarativeTextEdit::focusOutEvent(QFocusEvent *event) -{ - Q_D(const QDeclarativeTextEdit); - if (d->showInputPanelOnFocus && !isReadOnly()) { - closeSoftwareInputPanel(); - } - QDeclarativePaintedItem::focusOutEvent(event); -} - QT_END_NAMESPACE diff --git a/src/declarative/graphicsitems/qdeclarativetextedit_p.h b/src/declarative/graphicsitems/qdeclarativetextedit_p.h index a83b3db..d08f607 100644 --- a/src/declarative/graphicsitems/qdeclarativetextedit_p.h +++ b/src/declarative/graphicsitems/qdeclarativetextedit_p.h @@ -82,11 +82,10 @@ class Q_DECLARATIVE_EXPORT QDeclarativeTextEdit : public QDeclarativePaintedItem Q_PROPERTY(int cursorPosition READ cursorPosition WRITE setCursorPosition NOTIFY cursorPositionChanged) Q_PROPERTY(QRect cursorRectangle READ cursorRectangle NOTIFY cursorRectangleChanged) Q_PROPERTY(QDeclarativeComponent* cursorDelegate READ cursorDelegate WRITE setCursorDelegate NOTIFY cursorDelegateChanged) - Q_PROPERTY(int selectionStart READ selectionStart WRITE setSelectionStart NOTIFY selectionStartChanged) - Q_PROPERTY(int selectionEnd READ selectionEnd WRITE setSelectionEnd NOTIFY selectionEndChanged) + Q_PROPERTY(int selectionStart READ selectionStart NOTIFY selectionStartChanged) + Q_PROPERTY(int selectionEnd READ selectionEnd NOTIFY selectionEndChanged) Q_PROPERTY(QString selectedText READ selectedText NOTIFY selectionChanged) Q_PROPERTY(bool focusOnPress READ focusOnPress WRITE setFocusOnPress NOTIFY focusOnPressChanged) - Q_PROPERTY(bool showInputPanelOnFocus READ showInputPanelOnFocus WRITE setShowInputPanelOnFocus NOTIFY showInputPanelOnFocusChanged) Q_PROPERTY(bool persistentSelection READ persistentSelection WRITE setPersistentSelection NOTIFY persistentSelectionChanged) Q_PROPERTY(qreal textMargin READ textMargin WRITE setTextMargin NOTIFY textMarginChanged) Q_PROPERTY(Qt::InputMethodHints inputMethodHints READ inputMethodHints WRITE setInputMethodHints) @@ -160,19 +159,13 @@ public: void setCursorDelegate(QDeclarativeComponent*); int selectionStart() const; - void setSelectionStart(int); - int selectionEnd() const; - void setSelectionEnd(int); QString selectedText() const; bool focusOnPress() const; void setFocusOnPress(bool on); - bool showInputPanelOnFocus() const; - void setShowInputPanelOnFocus(bool showOnFocus); - bool persistentSelection() const; void setPersistentSelection(bool on); @@ -225,14 +218,16 @@ Q_SIGNALS: void persistentSelectionChanged(bool isPersistentSelection); void textMarginChanged(qreal textMargin); void selectByMouseChanged(bool selectByMouse); - void showInputPanelOnFocusChanged(bool showOnFocus); public Q_SLOTS: void selectAll(); void selectWord(); + void select(int start, int end); +#ifndef QT_NO_CLIPBOARD void cut(); void copy(); void paste(); +#endif private Q_SLOTS: void updateImgCache(const QRectF &rect); @@ -252,7 +247,6 @@ protected: void keyPressEvent(QKeyEvent *); void keyReleaseEvent(QKeyEvent *); void focusInEvent(QFocusEvent *event); - void focusOutEvent(QFocusEvent *event); // mouse filter? void mousePressEvent(QGraphicsSceneMouseEvent *event); diff --git a/src/declarative/graphicsitems/qdeclarativetextedit_p_p.h b/src/declarative/graphicsitems/qdeclarativetextedit_p_p.h index 8e1d630..4092e65 100644 --- a/src/declarative/graphicsitems/qdeclarativetextedit_p_p.h +++ b/src/declarative/graphicsitems/qdeclarativetextedit_p_p.h @@ -70,12 +70,17 @@ public: QDeclarativeTextEditPrivate() : color("black"), hAlign(QDeclarativeTextEdit::AlignLeft), vAlign(QDeclarativeTextEdit::AlignTop), imgDirty(true), dirty(false), richText(false), cursorVisible(false), focusOnPress(true), - showInputPanelOnFocus(true), persistentSelection(true), textMargin(0.0), lastSelectionStart(0), - lastSelectionEnd(0), cursorComponent(0), cursor(0), format(QDeclarativeTextEdit::AutoText), - document(0), wrapMode(QDeclarativeTextEdit::NoWrap), + showInputPanelOnFocus(true), clickCausedFocus(false), persistentSelection(true), textMargin(0.0), + lastSelectionStart(0), lastSelectionEnd(0), cursorComponent(0), cursor(0), + format(QDeclarativeTextEdit::AutoText), document(0), wrapMode(QDeclarativeTextEdit::NoWrap), selectByMouse(false), yoff(0) { +#ifdef Q_OS_SYMBIAN + if (QSysInfo::symbianVersion() == QSysInfo::SV_SF_1 || QSysInfo::symbianVersion() == QSysInfo::SV_SF_3) { + showInputPanelOnFocus = false; + } +#endif } void init(); @@ -102,6 +107,7 @@ public: bool cursorVisible : 1; bool focusOnPress : 1; bool showInputPanelOnFocus : 1; + bool clickCausedFocus : 1; bool persistentSelection : 1; qreal textMargin; int lastSelectionStart; diff --git a/src/declarative/graphicsitems/qdeclarativetextinput.cpp b/src/declarative/graphicsitems/qdeclarativetextinput.cpp index ea958ef..633c01e 100644 --- a/src/declarative/graphicsitems/qdeclarativetextinput.cpp +++ b/src/declarative/graphicsitems/qdeclarativetextinput.cpp @@ -46,6 +46,7 @@ #include <qdeclarativeinfo.h> #include <QValidator> +#include <QTextCursor> #include <QApplication> #include <QFontMetrics> #include <QPainter> @@ -55,17 +56,20 @@ QT_BEGIN_NAMESPACE /*! \qmlclass TextInput QDeclarativeTextInput \since 4.7 - \brief The TextInput item allows you to add an editable line of text to a scene. + \brief The TextInput item displays an editable line of text. \inherits Item - TextInput can only display a single line of text, and can only display - plain text. However it can provide addition input constraints on the text. + The TextInput element displays a single line of editable plain text. - Input constraints include setting a QValidator, an input mask, or a - maximum input length. + TextInput is used to accept a line of text input. Input constraints + can be placed on a TextInput item (for example, through a \l validator or \l inputMask), + and setting \l echoMode to an appropriate value enables TextInput to be used for + a password input field. On Mac OS X, the Up/Down key bindings for Home/End are explicitly disabled. If you want such bindings (on any platform), you will need to construct them in QML. + + \sa TextEdit, Text */ QDeclarativeTextInput::QDeclarativeTextInput(QDeclarativeItem* parent) : QDeclarativePaintedItem(*(new QDeclarativeTextInputPrivate), parent) @@ -248,7 +252,12 @@ QColor QDeclarativeTextInput::color() const void QDeclarativeTextInput::setColor(const QColor &c) { Q_D(QDeclarativeTextInput); - d->color = c; + if (c != d->color) { + d->color = c; + clearCache(); + update(); + emit colorChanged(c); + } } @@ -429,10 +438,12 @@ void QDeclarativeTextInput::setCursorPosition(int cp) Returns a Rect which encompasses the cursor, but which may be larger than is required. Ignores custom cursor delegates. */ -QRect QDeclarativeTextInput::cursorRect() const +QRect QDeclarativeTextInput::cursorRectangle() const { Q_D(const QDeclarativeTextInput); - return d->control->cursorRect(); + QRect r = d->control->cursorRect(); + r.setHeight(r.height()-1); // Make consistent with TextEdit (QLineControl inexplicably adds 1) + return r; } /*! @@ -454,15 +465,6 @@ int QDeclarativeTextInput::selectionStart() const return d->lastSelectionStart; } -void QDeclarativeTextInput::setSelectionStart(int s) -{ - Q_D(QDeclarativeTextInput); - if(d->lastSelectionStart == s || s < 0 || s > text().length()) - return; - d->lastSelectionStart = s; - d->control->setSelection(s, d->lastSelectionEnd - s); -} - /*! \qmlproperty int TextInput::selectionEnd @@ -482,13 +484,12 @@ int QDeclarativeTextInput::selectionEnd() const return d->lastSelectionEnd; } -void QDeclarativeTextInput::setSelectionEnd(int s) +void QDeclarativeTextInput::select(int start, int end) { Q_D(QDeclarativeTextInput); - if(d->lastSelectionEnd == s || s < 0 || s > text().length()) + if (start < 0 || end < 0 || start > d->control->text().length() || end > d->control->text().length()) return; - d->lastSelectionEnd = s; - d->control->setSelection(d->lastSelectionStart, s - d->lastSelectionStart); + d->control->setSelection(start, end-start); } /*! @@ -560,7 +561,7 @@ void QDeclarativeTextInput::setAutoScroll(bool b) /*! \qmlclass IntValidator QIntValidator - This element provides a validator for integer values + This element provides a validator for integer values. */ /*! \qmlproperty int IntValidator::top @@ -603,10 +604,14 @@ void QDeclarativeTextInput::setAutoScroll(bool b) \qmlproperty enumeration DoubleValidator::notation This property holds the notation of how a string can describe a number. - The values for this property are DoubleValidator.StandardNotation or DoubleValidator.ScientificNotation. - If this property is set to DoubleValidator.ScientificNotation, the written number may have an exponent part(i.e. 1.5E-2). + The possible values for this property are: + + \list + \o DoubleValidator.StandardNotation + \o DoubleValidator.ScientificNotation (default) + \endlist - By default, this property is set to DoubleValidator.ScientificNotation. + If this property is set to DoubleValidator.ScientificNotation, the written number may have an exponent part (e.g. 1.5E-2). */ /*! @@ -835,6 +840,19 @@ void QDeclarativeTextInput::moveCursor() } /*! + \qmlmethod rect TextInput::positionToRectangle(int x) +*/ +QRectF QDeclarativeTextInput::positionToRectangle(int x) const +{ + Q_D(const QDeclarativeTextInput); + QFontMetrics fm = QFontMetrics(d->font); + return QRectF(d->control->cursorToX(x)-d->hscroll, + 0.0, + d->control->cursorWidth(), + cursorRectangle().height()); +} + +/*! \qmlmethod int TextInput::positionAt(int x) This function returns the character position at @@ -845,10 +863,10 @@ void QDeclarativeTextInput::moveCursor() This means that for all x values before the first character this function returns 0, and for all x values after the last character this function returns text.length. */ -int QDeclarativeTextInput::positionAt(int x) +int QDeclarativeTextInput::positionAt(int x) const { Q_D(const QDeclarativeTextInput); - return d->control->xToPos(x - d->hscroll); + return d->control->xToPos(x + d->hscroll); } void QDeclarativeTextInputPrivate::focusChanged(bool hasFocus) @@ -885,6 +903,22 @@ void QDeclarativeTextInput::keyPressEvent(QKeyEvent* ev) QDeclarativePaintedItem::keyPressEvent(ev); } +/*! +\overload +Handles the given mouse \a event. +*/ +void QDeclarativeTextInput::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) +{ + Q_D(QDeclarativeTextInput); + if (d->selectByMouse) { + int cursor = d->xToPos(event->pos().x()); + d->control->selectWordAtPos(cursor); + event->setAccepted(true); + } else { + QDeclarativePaintedItem::mouseDoubleClickEvent(event); + } +} + void QDeclarativeTextInput::mousePressEvent(QGraphicsSceneMouseEvent *event) { Q_D(QDeclarativeTextInput); @@ -897,12 +931,17 @@ void QDeclarativeTextInput::mousePressEvent(QGraphicsSceneMouseEvent *event) p = p->parentItem(); } setFocus(true); - if (hasFocus() == hadFocus && d->showInputPanelOnFocus && !isReadOnly()) { - // re-open input panel on press w already focused - openSoftwareInputPanel(); + if (d->showInputPanelOnFocus) { + if (hasFocus() && hadFocus && !isReadOnly()) { + // re-open input panel on press if already focused + openSoftwareInputPanel(); + } + } else { // show input panel on click + if (hasFocus() && !hadFocus) { + d->clickCausedFocus = true; + } } } - bool mark = event->modifiers() & Qt::ShiftModifier; int cursor = d->xToPos(event->pos().x()); d->control->moveCursor(cursor, mark); @@ -927,6 +966,16 @@ Handles the given mouse \a event. void QDeclarativeTextInput::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { Q_D(QDeclarativeTextInput); + if (!d->showInputPanelOnFocus) { // input panel on click + if (d->focusOnPress && !isReadOnly() && boundingRect().contains(event->pos())) { + if (QGraphicsView * view = qobject_cast<QGraphicsView*>(qApp->focusWidget())) { + if (view->scene() && view->scene() == scene()) { + qt_widget_private(view)->handleSoftwareInputPanel(event->button(), d->clickCausedFocus); + } + } + } + } + d->clickCausedFocus = false; d->control->processEvent(event); if (!event->isAccepted()) QDeclarativePaintedItem::mouseReleaseEvent(event); @@ -943,10 +992,9 @@ bool QDeclarativeTextInput::event(QEvent* ev) case QEvent::GraphicsSceneMousePress: case QEvent::GraphicsSceneMouseMove: case QEvent::GraphicsSceneMouseRelease: + case QEvent::GraphicsSceneMouseDoubleClick: break; default: - if (ev->type() == QEvent::GraphicsSceneMouseDoubleClick && !d->selectByMouse) - break; handled = d->control->processEvent(ev); if (ev->type() == QEvent::InputMethod) updateSize(); @@ -1021,7 +1069,6 @@ void QDeclarativeTextInput::drawContents(QPainter *p, const QRect &r) d->hscroll -= minLB; offset = QPoint(d->hscroll, 0); } - d->control->draw(p, offset, r, flags); p->restore(); @@ -1059,12 +1106,27 @@ QVariant QDeclarativeTextInput::inputMethodQuery(Qt::InputMethodQuery property) } } +/*! + \qmlmethod void TextInput::selectAll() + + Causes all text to be selected. +*/ void QDeclarativeTextInput::selectAll() { Q_D(QDeclarativeTextInput); d->control->setSelection(0, d->control->text().length()); } +/*! + \qmlmethod void TextInput::selectWord() + + Causes the word closest to the current cursor position to be selected. +*/ +void QDeclarativeTextInput::selectWord() +{ + Q_D(QDeclarativeTextInput); + d->control->selectWordAtPos(d->control->cursor()); +} /*! \qmlproperty bool TextInput::smooth @@ -1183,26 +1245,37 @@ void QDeclarativeTextInput::moveCursorSelection(int position) customizing when you want the input keyboard to be shown and hidden in your application. - By default input panels are shown when TextInput element gains focus and hidden - when the focus is lost. You can disable the automatic behavior by setting the - property showInputPanelOnFocus to false and use functions openSoftwareInputPanel() - and closeSoftwareInputPanel() to implement the behavior you want. + By default the opening of input panels follows the platform style. On Symbian^1 and + Symbian^3 -based devices the panels are opened by clicking TextInput. On other platforms + the panels are automatically opened when TextInput element gains focus. Input panels are + always closed if no editor owns focus. + + . You can disable the automatic behavior by setting the property \c focusOnPress to false + and use functions openSoftwareInputPanel() and closeSoftwareInputPanel() to implement + the behavior you want. Only relevant on platforms, which provide virtual keyboards. - \code + \qml import Qt 4.7 TextInput { id: textInput text: "Hello world!" - showInputPanelOnFocus: false + focusOnPress: false MouseArea { anchors.fill: parent - onClicked: textInput.openSoftwareInputPanel() + onClicked: { + if (!textInput.focus) { + textInput.focus = true; + textInput.openSoftwareInputPanel(); + } else { + textInput.focus = false; + } + } + onPressAndHold: textInput.closeSoftwareInputPanel(); } - onFocusChanged: if (!focus) closeSoftwareInputPanel() } - \endcode + \endqml */ void QDeclarativeTextInput::openSoftwareInputPanel() { @@ -1223,26 +1296,37 @@ void QDeclarativeTextInput::openSoftwareInputPanel() for customizing when you want the input keyboard to be shown and hidden in your application. - By default input panels are shown when TextInput element gains focus and hidden - when the focus is lost. You can disable the automatic behavior by setting the - property showInputPanelOnFocus to false and use functions openSoftwareInputPanel() - and closeSoftwareInputPanel() to implement the behavior you want. + By default the opening of input panels follows the platform style. On Symbian^1 and + Symbian^3 -based devices the panels are opened by clicking TextInput. On other platforms + the panels are automatically opened when TextInput element gains focus. Input panels are + always closed if no editor owns focus. + + . You can disable the automatic behavior by setting the property \c focusOnPress to false + and use functions openSoftwareInputPanel() and closeSoftwareInputPanel() to implement + the behavior you want. Only relevant on platforms, which provide virtual keyboards. - \code + \qml import Qt 4.7 TextInput { id: textInput text: "Hello world!" - showInputPanelOnFocus: false + focusOnPress: false MouseArea { anchors.fill: parent - onClicked: textInput.openSoftwareInputPanel() + onClicked: { + if (!textInput.focus) { + textInput.focus = true; + textInput.openSoftwareInputPanel(); + } else { + textInput.focus = false; + } + } + onPressAndHold: textInput.closeSoftwareInputPanel(); } - onFocusChanged: if (!focus) closeSoftwareInputPanel() } - \endcode + \endqml */ void QDeclarativeTextInput::closeSoftwareInputPanel() { @@ -1257,54 +1341,22 @@ void QDeclarativeTextInput::closeSoftwareInputPanel() } } -/*! - \qmlproperty bool TextInput::showInputPanelOnFocus - Whether input panels are automatically shown when TextInput element gains - focus and hidden when focus is lost. By default this is set to true. - - Only relevant on platforms, which provide virtual keyboards. -*/ -bool QDeclarativeTextInput::showInputPanelOnFocus() const -{ - Q_D(const QDeclarativeTextInput); - return d->showInputPanelOnFocus; -} - -void QDeclarativeTextInput::setShowInputPanelOnFocus(bool showOnFocus) -{ - Q_D(QDeclarativeTextInput); - if (d->showInputPanelOnFocus == showOnFocus) - return; - - d->showInputPanelOnFocus = showOnFocus; - - emit showInputPanelOnFocusChanged(d->showInputPanelOnFocus); -} - void QDeclarativeTextInput::focusInEvent(QFocusEvent *event) { Q_D(const QDeclarativeTextInput); - if (d->showInputPanelOnFocus && !isReadOnly() && event->reason() != Qt::ActiveWindowFocusReason) { - openSoftwareInputPanel(); + if (d->showInputPanelOnFocus) { + if (d->focusOnPress && !isReadOnly()) { + openSoftwareInputPanel(); + } } QDeclarativePaintedItem::focusInEvent(event); } -void QDeclarativeTextInput::focusOutEvent(QFocusEvent *event) -{ - Q_D(const QDeclarativeTextInput); - if (d->showInputPanelOnFocus && !isReadOnly()) { - closeSoftwareInputPanel(); - } - QDeclarativePaintedItem::focusOutEvent(event); -} - void QDeclarativeTextInputPrivate::init() { Q_Q(QDeclarativeTextInput); control->setCursorWidth(1); control->setPasswordCharacter(QLatin1Char('*')); - control->setLayoutDirection(Qt::LeftToRight); q->setSmooth(smooth); q->setAcceptedMouseButtons(Qt::LeftButton); q->setFlag(QGraphicsItem::ItemHasNoContents, false); diff --git a/src/declarative/graphicsitems/qdeclarativetextinput_p.h b/src/declarative/graphicsitems/qdeclarativetextinput_p.h index 9d58f13..c539bd3 100644 --- a/src/declarative/graphicsitems/qdeclarativetextinput_p.h +++ b/src/declarative/graphicsitems/qdeclarativetextinput_p.h @@ -72,10 +72,10 @@ class Q_DECLARATIVE_EXPORT QDeclarativeTextInput : public QDeclarativePaintedIte Q_PROPERTY(bool readOnly READ isReadOnly WRITE setReadOnly NOTIFY readOnlyChanged) Q_PROPERTY(bool cursorVisible READ isCursorVisible WRITE setCursorVisible NOTIFY cursorVisibleChanged) Q_PROPERTY(int cursorPosition READ cursorPosition WRITE setCursorPosition NOTIFY cursorPositionChanged) - Q_PROPERTY(QRect cursorRect READ cursorRect NOTIFY cursorPositionChanged) + Q_PROPERTY(QRect cursorRectangle READ cursorRectangle NOTIFY cursorPositionChanged) Q_PROPERTY(QDeclarativeComponent *cursorDelegate READ cursorDelegate WRITE setCursorDelegate NOTIFY cursorDelegateChanged) - Q_PROPERTY(int selectionStart READ selectionStart WRITE setSelectionStart NOTIFY selectionStartChanged) - Q_PROPERTY(int selectionEnd READ selectionEnd WRITE setSelectionEnd NOTIFY selectionEndChanged) + Q_PROPERTY(int selectionStart READ selectionStart NOTIFY selectionStartChanged) + Q_PROPERTY(int selectionEnd READ selectionEnd NOTIFY selectionEndChanged) Q_PROPERTY(QString selectedText READ selectedText NOTIFY selectedTextChanged) Q_PROPERTY(int maximumLength READ maxLength WRITE setMaxLength NOTIFY maximumLengthChanged) @@ -88,7 +88,6 @@ class Q_DECLARATIVE_EXPORT QDeclarativeTextInput : public QDeclarativePaintedIte Q_PROPERTY(bool acceptableInput READ hasAcceptableInput NOTIFY acceptableInputChanged) Q_PROPERTY(EchoMode echoMode READ echoMode WRITE setEchoMode NOTIFY echoModeChanged) Q_PROPERTY(bool focusOnPress READ focusOnPress WRITE setFocusOnPress NOTIFY focusOnPressChanged) - Q_PROPERTY(bool showInputPanelOnFocus READ showInputPanelOnFocus WRITE setShowInputPanelOnFocus NOTIFY showInputPanelOnFocusChanged) Q_PROPERTY(QString passwordCharacter READ passwordCharacter WRITE setPasswordCharacter NOTIFY passwordCharacterChanged) Q_PROPERTY(QString displayText READ displayText NOTIFY displayTextChanged) Q_PROPERTY(bool autoScroll READ autoScroll WRITE setAutoScroll NOTIFY autoScrollChanged) @@ -112,7 +111,8 @@ public: }; //Auxilliary functions needed to control the TextInput from QML - Q_INVOKABLE int positionAt(int x); + Q_INVOKABLE int positionAt(int x) const; + Q_INVOKABLE QRectF positionToRectangle(int x) const; Q_INVOKABLE void moveCursorSelection(int pos); Q_INVOKABLE void openSoftwareInputPanel(); @@ -145,13 +145,10 @@ public: int cursorPosition() const; void setCursorPosition(int cp); - QRect cursorRect() const; + QRect cursorRectangle() const; int selectionStart() const; - void setSelectionStart(int); - int selectionEnd() const; - void setSelectionEnd(int); QString selectedText() const; @@ -179,9 +176,6 @@ public: bool focusOnPress() const; void setFocusOnPress(bool); - bool showInputPanelOnFocus() const; - void setShowInputPanelOnFocus(bool showOnFocus); - bool autoScroll() const; void setAutoScroll(bool); @@ -218,7 +212,6 @@ Q_SIGNALS: void focusOnPressChanged(bool focusOnPress); void autoScrollChanged(bool autoScroll); void selectByMouseChanged(bool selectByMouse); - void showInputPanelOnFocusChanged(bool showOnFocus); protected: virtual void geometryChanged(const QRectF &newGeometry, @@ -227,13 +220,15 @@ protected: void mousePressEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); void keyPressEvent(QKeyEvent* ev); bool event(QEvent *e); void focusInEvent(QFocusEvent *event); - void focusOutEvent(QFocusEvent *event); public Q_SLOTS: void selectAll(); + void selectWord(); + void select(int start, int end); private Q_SLOTS: void updateSize(bool needsRedraw = true); diff --git a/src/declarative/graphicsitems/qdeclarativetextinput_p_p.h b/src/declarative/graphicsitems/qdeclarativetextinput_p_p.h index f44d014..6865147 100644 --- a/src/declarative/graphicsitems/qdeclarativetextinput_p_p.h +++ b/src/declarative/graphicsitems/qdeclarativetextinput_p_p.h @@ -72,9 +72,15 @@ public: color((QRgb)0), style(QDeclarativeText::Normal), styleColor((QRgb)0), hAlign(QDeclarativeTextInput::AlignLeft), hscroll(0), oldScroll(0), focused(false), focusOnPress(true), - showInputPanelOnFocus(true), cursorVisible(false), autoScroll(true), - selectByMouse(false) + showInputPanelOnFocus(true), clickCausedFocus(false), cursorVisible(false), + autoScroll(true), selectByMouse(false) { +#ifdef Q_OS_SYMBIAN + if (QSysInfo::symbianVersion() == QSysInfo::SV_SF_1 || QSysInfo::symbianVersion() == QSysInfo::SV_SF_3) { + showInputPanelOnFocus = false; + } +#endif + } ~QDeclarativeTextInputPrivate() @@ -116,6 +122,7 @@ public: bool focused; bool focusOnPress; bool showInputPanelOnFocus; + bool clickCausedFocus; bool cursorVisible; bool autoScroll; bool selectByMouse; diff --git a/src/declarative/graphicsitems/qdeclarativevisualitemmodel.cpp b/src/declarative/graphicsitems/qdeclarativevisualitemmodel.cpp index c6ee46f..5092349 100644 --- a/src/declarative/graphicsitems/qdeclarativevisualitemmodel.cpp +++ b/src/declarative/graphicsitems/qdeclarativevisualitemmodel.cpp @@ -113,17 +113,19 @@ public: \since 4.7 \brief The VisualItemModel allows items to be provided to a view. - The children of the VisualItemModel are provided in a model which - can be used in a view. Note that no delegate should be - provided to a view since the VisualItemModel contains the - visual delegate (items). + A VisualItemModel contains the visual items to be used in a view. + When a VisualItemModel is used in a view, the view does not require + a delegate since the VisualItemModel already contains the visual + delegate (items). An item can determine its index within the - model via the VisualItemModel.index attached property. + model via the \l{VisualItemModel::index}{index} attached property. The example below places three colored rectangles in a ListView. \code - Item { + import Qt 4.7 + + Rectangle { VisualItemModel { id: itemModel Rectangle { height: 30; width: 80; color: "red" } @@ -137,12 +139,23 @@ public: } } \endcode + + \image visualitemmodel.png + + \sa {declarative/modelviews/visualitemmodel}{VisualItemModel example} */ QDeclarativeVisualItemModel::QDeclarativeVisualItemModel(QObject *parent) : QDeclarativeVisualModel(*(new QDeclarativeVisualItemModelPrivate), parent) { } +/*! + \qmlattachedproperty int VisualItemModel::index + This attached property holds the index of this delegate's item within the model. + + It is attached to each instance of the delegate. +*/ + QDeclarativeListProperty<QDeclarativeItem> QDeclarativeVisualItemModel::children() { Q_D(QDeclarativeVisualItemModel); @@ -605,30 +618,15 @@ QDeclarativeVisualDataModelData *QDeclarativeVisualDataModelPrivate::data(QObjec A VisualDataModel encapsulates a model and the delegate that will be instantiated for items in the model. - It is usually not necessary to create a VisualDataModel directly, - since the QML views will create one internally. + It is usually not necessary to create VisualDataModel elements. + However, it can be useful for manipulating and accessing the \l modelIndex + when a QAbstractItemModel subclass is used as the + model. Also, VisualDataModel is used together with \l Package to + provide delegates to multiple views. The example below illustrates using a VisualDataModel with a ListView. - \code - VisualDataModel { - id: visualModel - model: myModel - delegate: Component { - Rectangle { - height: 25 - width: 100 - Text { text: "Name:" + name} - } - } - } - ListView { - width: 100 - height: 100 - anchors.fill: parent - model: visualModel - } - \endcode + \snippet doc/src/snippets/declarative/visualdatamodel.qml 0 */ QDeclarativeVisualDataModel::QDeclarativeVisualDataModel() @@ -803,56 +801,22 @@ void QDeclarativeVisualDataModel::setDelegate(QDeclarativeComponent *delegate) /*! \qmlproperty QModelIndex VisualDataModel::rootIndex - QAbstractItemModel provides a heirachical tree of data, whereas + QAbstractItemModel provides a hierarchical tree of data, whereas QML only operates on list data. \c rootIndex allows the children of any node in a QAbstractItemModel to be provided by this model. This property only affects models of type QAbstractItemModel. - \code - // main.cpp + For example, here is a simple interactive file system browser. + When a directory name is clicked, the view's \c rootIndex is set to the + QModelIndex node of the clicked directory, thus updating the view to show + the new directory's contents. - int main(int argc, char ** argv) - { - QApplication app(argc, argv); - - QDeclarativeView view; - - QDirModel model; - view.rootContext()->setContextProperty("myModel", &model); - - view.setSource(QUrl("qrc:view.qml")); - view.show(); - - return app.exec(); - } - - #include "main.moc" - \endcode - - \code - // view.qml - import Qt 4.7 - - ListView { - id: view - width: 200 - height: 200 - model: VisualDataModel { - model: myModel - delegate: Component { - Rectangle { - height: 25; width: 200 - Text { text: filePath } - MouseArea { - anchors.fill: parent; - onClicked: if (hasModelChildren) view.model.rootIndex = view.model.modelIndex(index) - } - } - } - } - } - \endcode + \c main.cpp: + \snippet doc/src/snippets/declarative/visualdatamodel_rootindex/main.cpp 0 + + \c view.qml: + \snippet doc/src/snippets/declarative/visualdatamodel_rootindex/view.qml 0 \sa modelIndex(), parentModelIndex() */ @@ -884,7 +848,7 @@ void QDeclarativeVisualDataModel::setRootIndex(const QVariant &root) /*! \qmlmethod QModelIndex VisualDataModel::modelIndex(int index) - QAbstractItemModel provides a heirachical tree of data, whereas + QAbstractItemModel provides a hierarchical tree of data, whereas QML only operates on list data. This function assists in using tree models in QML. @@ -904,7 +868,7 @@ QVariant QDeclarativeVisualDataModel::modelIndex(int idx) const /*! \qmlmethod QModelIndex VisualDataModel::parentModelIndex() - QAbstractItemModel provides a heirachical tree of data, whereas + QAbstractItemModel provides a hierarchical tree of data, whereas QML only operates on list data. This function assists in using tree models in QML. @@ -998,10 +962,10 @@ QDeclarativeVisualDataModel::ReleaseFlags QDeclarativeVisualDataModel::release(Q The \a parts property selects a VisualDataModel which creates delegates from the part named. This is used in conjunction with - the Package element. + the \l Package element. For example, the code below selects a model which creates - delegates named \e list from a Package: + delegates named \e list from a \l Package: \code VisualDataModel { diff --git a/src/declarative/graphicsitems/qdeclarativevisualitemmodel_p.h b/src/declarative/graphicsitems/qdeclarativevisualitemmodel_p.h index 0bdbbcf..079c9e6 100644 --- a/src/declarative/graphicsitems/qdeclarativevisualitemmodel_p.h +++ b/src/declarative/graphicsitems/qdeclarativevisualitemmodel_p.h @@ -54,11 +54,6 @@ Q_DECLARE_METATYPE(QModelIndex) QT_BEGIN_NAMESPACE QT_MODULE(Declarative) -/***************************************************************************** - ***************************************************************************** - XXX Experimental - ***************************************************************************** -*****************************************************************************/ class QDeclarativeItem; class QDeclarativeComponent; diff --git a/src/declarative/qml/parser/qdeclarativejslexer.cpp b/src/declarative/qml/parser/qdeclarativejslexer.cpp index 975ad4c..fcaaece 100644 --- a/src/declarative/qml/parser/qdeclarativejslexer.cpp +++ b/src/declarative/qml/parser/qdeclarativejslexer.cpp @@ -57,7 +57,7 @@ #include <string.h> QT_BEGIN_NAMESPACE -Q_DECL_IMPORT extern double qstrtod(const char *s00, char const **se, bool *ok); +Q_CORE_EXPORT double qstrtod(const char *s00, char const **se, bool *ok); QT_END_NAMESPACE QT_QML_BEGIN_NAMESPACE diff --git a/src/declarative/qml/qdeclarative.h b/src/declarative/qml/qdeclarative.h index d75f0a8..53ff51c 100644 --- a/src/declarative/qml/qdeclarative.h +++ b/src/declarative/qml/qdeclarative.h @@ -67,7 +67,7 @@ QT_BEGIN_HEADER QML_DECLARE_TYPE_HASMETATYPE(INTERFACE) enum { /* TYPEINFO flags */ - QML_HAS_ATTACHED_PROPERTIES = 0x01, + QML_HAS_ATTACHED_PROPERTIES = 0x01 }; #define QML_DECLARE_TYPEINFO(TYPE, FLAGS) \ diff --git a/src/declarative/qml/qdeclarativecomponent.cpp b/src/declarative/qml/qdeclarativecomponent.cpp index 9847079..55ee783 100644 --- a/src/declarative/qml/qdeclarativecomponent.cpp +++ b/src/declarative/qml/qdeclarativecomponent.cpp @@ -78,7 +78,7 @@ class QByteArray; \since 4.7 \brief The Component element encapsulates a QML component description. - Components are reusable, encapsulated Qml element with a well-defined interface. + Components are reusable, encapsulated QML elements with well-defined interfaces. They are often defined in \l {qdeclarativedocuments.html}{Component Files}. The \e Component element allows defining components within a QML file. @@ -547,16 +547,18 @@ QDeclarativeComponent::QDeclarativeComponent(QDeclarativeComponentPrivate &dd, Q /*! \qmlmethod object Component::createObject(parent) - Returns an object instance from this component, or null if object creation fails. + + Creates and returns an object instance of this component that will have the given + \a parent. Returns null if object creation fails. The object will be created in the same context as the one in which the component was created. This function will always return null when called on components which were not created in QML. - Note that if the returned object is to be displayed, its \c parent must be set to - an existing item in a scene, or else the object will not be visible. The parent - argument is required to help you avoid this, you must explicitly pass in null if - you wish to create an object without setting a parent. + If you wish to create an object without setting a parent, specify \c null for + the \a parent value. Note that if the returned object is to be displayed, you + must provide a valid \a parent value or set the returned object's \l{Item::parent}{parent} + property, or else the object will not be visible. */ /*! diff --git a/src/declarative/qml/qdeclarativecontext.cpp b/src/declarative/qml/qdeclarativecontext.cpp index 6a13f15..2221d78 100644 --- a/src/declarative/qml/qdeclarativecontext.cpp +++ b/src/declarative/qml/qdeclarativecontext.cpp @@ -116,7 +116,7 @@ QDeclarativeContextPrivate::QDeclarativeContextPrivate() All properties added explicitly by QDeclarativeContext::setContextProperty() take precedence over the context object's properties. - Contexts form a hierarchy. The root of this heirarchy is the QDeclarativeEngine's + Contexts form a hierarchy. The root of this hierarchy is the QDeclarativeEngine's \l {QDeclarativeEngine::rootContext()}{root context}. A component instance can access the data in its own context, as well as all its ancestor contexts. Data can be made available to all instances by modifying the diff --git a/src/declarative/qml/qdeclarativecontext_p.h b/src/declarative/qml/qdeclarativecontext_p.h index 6b6cd0a..1f5aaf1 100644 --- a/src/declarative/qml/qdeclarativecontext_p.h +++ b/src/declarative/qml/qdeclarativecontext_p.h @@ -108,7 +108,7 @@ public: class QDeclarativeComponentAttached; class QDeclarativeGuardedContextData; -class QDeclarativeContextData +class Q_AUTOTEST_EXPORT QDeclarativeContextData { public: QDeclarativeContextData(); diff --git a/src/declarative/qml/qdeclarativeengine.cpp b/src/declarative/qml/qdeclarativeengine.cpp index 2f2ee08..0715624 100644 --- a/src/declarative/qml/qdeclarativeengine.cpp +++ b/src/declarative/qml/qdeclarativeengine.cpp @@ -155,14 +155,26 @@ void QDeclarativeEnginePrivate::defineModule() \qmlclass Qt QDeclarativeEnginePrivate \brief The QML global Qt object provides useful enums and functions from Qt. -The Qt object provides useful enums and functions from Qt, for use in all QML files. +The \c Qt object provides useful enums and functions from Qt, for use in all QML files. + +The \c Qt object is not a QML element; it cannot be instantiated. It is a global object +with enums and functions. To use it, call the members of the global \c Qt object directly. +For example: + +\qml +import Qt 4.7 + +Text { + color: Qt.rgba(255, 0, 0, 1) + text: Qt.md5("hello, world") +} +\endqml -You do not create instances of this type, but instead use the members of the global "Qt" object. \section1 Enums The Qt object contains all enums in the Qt namespace. For example, you can -access the AlignLeft member of the Qt::AlignmentFlag enum with \c Qt.AlignLeft. +access the \c AlignLeft member of the \c Qt::AlignmentFlag enum with \c Qt.AlignLeft. For a full list of enums, see the \l{Qt Namespace} documentation. @@ -172,14 +184,14 @@ data types. This is primarily useful when setting the properties of an item when the property has one of the following types: \list -\o \c color - use \l{Qt::rgba()}{Qt.rgba()}, \l{Qt::darker()}{Qt.darker()}, \l{Qt::lighter()}{Qt.lighter()} or \l{Qt::tint()}{Qt.tint()} +\o \c color - use \l{Qt::rgba()}{Qt.rgba()}, \l{Qt::hsla()}{Qt.hsla()}, \l{Qt::darker()}{Qt.darker()}, \l{Qt::lighter()}{Qt.lighter()} or \l{Qt::tint()}{Qt.tint()} \o \c rect - use \l{Qt::rect()}{Qt.rect()} \o \c point - use \l{Qt::point()}{Qt.point()} \o \c size - use \l{Qt::size()}{Qt.size()} \o \c vector3d - use \l{Qt::vector3d()}{Qt.vector3d()} \endlist -There are also string based constructors for these types, see \l{qdeclarativebasictypes.html}{QML Basic Types}. +There are also string based constructors for these types. See \l{qdeclarativebasictypes.html}{QML Basic Types} for more information. \section1 Date/Time Formatters @@ -200,8 +212,8 @@ items from files or strings. See \l{Dynamic Object Management} for an overview of their use. \list - \o \l{Qt::createComponent}{object Qt.createComponent(url)} - \o \l{Qt::createQmlObject}{object Qt.createQmlObject(string qml, object parent, string filepath)} + \o \l{Qt::createComponent()}{object Qt.createComponent(url)} + \o \l{Qt::createQmlObject()}{object Qt.createQmlObject(string qml, object parent, string filepath)} \endlist */ @@ -1036,14 +1048,15 @@ QString QDeclarativeEnginePrivate::urlToLocalFileOrQrc(const QUrl& url) /*! \qmlmethod object Qt::createComponent(url) -Returns a \l Component object created from the QML file at the specified \a url, +Returns a \l Component object created using the QML file at the specified \a url, or \c null if there was an error in creating the component. Call \l {Component::createObject()}{Component.createObject()} on the returned component to create an object instance of the component. -Here is an example. Remember that QML files that might be loaded -over the network cannot be expected to be ready immediately. +Here is an example. Notice it checks whether the component \l{Component::status}{status} is +\c Component.Ready before calling \l {Component::createObject()}{createObject()} +in case the QML file is loaded over a network and thus is not ready immediately. \snippet doc/src/snippets/declarative/componentCreation.js 0 \codeline @@ -1083,12 +1096,12 @@ QScriptValue QDeclarativeEnginePrivate::createComponent(QScriptContext *ctxt, QS /*! \qmlmethod object Qt::createQmlObject(string qml, object parent, string filepath) -Returns a new object created from the given \a string of QML with the specified \a parent, +Returns a new object created from the given \a string of QML which will have the specified \a parent, or \c null if there was an error in creating the object. If \a filepath is specified, it will be used for error reporting for the created object. -Example (where \c targetItem is the id of an existing QML item): +Example (where \c parentItem is the id of an existing QML item): \snippet doc/src/snippets/declarative/createQmlObject.qml 0 @@ -1364,7 +1377,7 @@ QScriptValue QDeclarativeEnginePrivate::formatDateTime(QScriptContext*ctxt, QScr /*! \qmlmethod color Qt::rgba(real red, real green, real blue, real alpha) -Returns a Color with the specified \c red, \c green, \c blue and \c alpha components. +Returns a color with the specified \c red, \c green, \c blue and \c alpha components. All components should be in the range 0-1 inclusive. */ QScriptValue QDeclarativeEnginePrivate::rgba(QScriptContext *ctxt, QScriptEngine *engine) @@ -1392,7 +1405,7 @@ QScriptValue QDeclarativeEnginePrivate::rgba(QScriptContext *ctxt, QScriptEngine /*! \qmlmethod color Qt::hsla(real hue, real saturation, real lightness, real alpha) -Returns a Color with the specified \c hue, \c saturation, \c lightness and \c alpha components. +Returns a color with the specified \c hue, \c saturation, \c lightness and \c alpha components. All components should be in the range 0-1 inclusive. */ QScriptValue QDeclarativeEnginePrivate::hsla(QScriptContext *ctxt, QScriptEngine *engine) @@ -1420,7 +1433,9 @@ QScriptValue QDeclarativeEnginePrivate::hsla(QScriptContext *ctxt, QScriptEngine /*! \qmlmethod rect Qt::rect(int x, int y, int width, int height) -Returns a Rect with the top-left corner at \c x, \c y and the specified \c width and \c height. +Returns a \c rect with the top-left corner at \c x, \c y and the specified \c width and \c height. + +The returned object has \c x, \c y, \c width and \c height attributes with the given values. */ QScriptValue QDeclarativeEnginePrivate::rect(QScriptContext *ctxt, QScriptEngine *engine) { diff --git a/src/declarative/qml/qdeclarativeimport.cpp b/src/declarative/qml/qdeclarativeimport.cpp index c658a31..a2e3831 100644 --- a/src/declarative/qml/qdeclarativeimport.cpp +++ b/src/declarative/qml/qdeclarativeimport.cpp @@ -823,7 +823,7 @@ void QDeclarativeImportDatabase::addPluginPath(const QString& path) qDebug() << "QDeclarativeImportDatabase::addPluginPath" << path; QUrl url = QUrl(path); - if (url.isRelative() || url.scheme() == QString::fromLocal8Bit("file")) { + if (url.isRelative() || url.scheme() == QLatin1String("file")) { QDir dir = QDir(path); filePluginPath.prepend(dir.canonicalPath()); } else { @@ -842,7 +842,7 @@ void QDeclarativeImportDatabase::addImportPath(const QString& path) QUrl url = QUrl(path); QString cPath; - if (url.isRelative() || url.scheme() == QString::fromLocal8Bit("file")) { + if (url.isRelative() || url.scheme() == QLatin1String("file")) { QDir dir = QDir(path); cPath = dir.canonicalPath(); } else { diff --git a/src/declarative/qml/qdeclarativeinstruction_p.h b/src/declarative/qml/qdeclarativeinstruction_p.h index dc5f2f8..4627eb3 100644 --- a/src/declarative/qml/qdeclarativeinstruction_p.h +++ b/src/declarative/qml/qdeclarativeinstruction_p.h @@ -158,7 +158,7 @@ public: // // Deferred creation // - Defer, /* defer */ + Defer /* defer */ }; QDeclarativeInstruction() : line(0) {} diff --git a/src/declarative/qml/qdeclarativepropertycache_p.h b/src/declarative/qml/qdeclarativepropertycache_p.h index b01e5cc..72cfeba 100644 --- a/src/declarative/qml/qdeclarativepropertycache_p.h +++ b/src/declarative/qml/qdeclarativepropertycache_p.h @@ -65,7 +65,7 @@ QT_BEGIN_NAMESPACE class QDeclarativeEngine; class QMetaProperty; -class QDeclarativePropertyCache : public QDeclarativeRefCount, public QDeclarativeCleanup +class Q_AUTOTEST_EXPORT QDeclarativePropertyCache : public QDeclarativeRefCount, public QDeclarativeCleanup { public: QDeclarativePropertyCache(QDeclarativeEngine *); diff --git a/src/declarative/qml/qdeclarativevaluetype.cpp b/src/declarative/qml/qdeclarativevaluetype.cpp index dbc25bb..c17ec95 100644 --- a/src/declarative/qml/qdeclarativevaluetype.cpp +++ b/src/declarative/qml/qdeclarativevaluetype.cpp @@ -47,6 +47,8 @@ QT_BEGIN_NAMESPACE +Q_DECL_IMPORT extern int qt_defaultDpi(); + template<typename T> int qmlRegisterValueTypeEnums(const char *qmlName) { @@ -909,6 +911,11 @@ void QDeclarativeFontValueType::setStrikeout(bool b) qreal QDeclarativeFontValueType::pointSize() const { + if (font.pointSizeF() == -1) { + if (dpi.isNull) + dpi = qt_defaultDpi(); + return font.pixelSize() * qreal(72.) / qreal(dpi); + } return font.pointSizeF(); } @@ -929,6 +936,11 @@ void QDeclarativeFontValueType::setPointSize(qreal size) int QDeclarativeFontValueType::pixelSize() const { + if (font.pixelSize() == -1) { + if (dpi.isNull) + dpi = qt_defaultDpi(); + return (font.pointSizeF() * dpi) / qreal(72.); + } return font.pixelSize(); } diff --git a/src/declarative/qml/qdeclarativevaluetype_p.h b/src/declarative/qml/qdeclarativevaluetype_p.h index 476c73d..4b1bbd6 100644 --- a/src/declarative/qml/qdeclarativevaluetype_p.h +++ b/src/declarative/qml/qdeclarativevaluetype_p.h @@ -55,6 +55,7 @@ #include "qdeclarativeproperty.h" #include "private/qdeclarativeproperty_p.h" +#include "private/qdeclarativenullablevalue_p_p.h" #include <QtCore/qobject.h> #include <QtCore/qrect.h> @@ -446,7 +447,7 @@ public: InBounce = QEasingCurve::InBounce, OutBounce = QEasingCurve::OutBounce, InOutBounce = QEasingCurve::InOutBounce, OutInBounce = QEasingCurve::OutInBounce, InCurve = QEasingCurve::InCurve, OutCurve = QEasingCurve::OutCurve, - SineCurve = QEasingCurve::SineCurve, CosineCurve = QEasingCurve::CosineCurve, + SineCurve = QEasingCurve::SineCurve, CosineCurve = QEasingCurve::CosineCurve }; QDeclarativeEasingValueType(QObject *parent = 0); @@ -547,6 +548,7 @@ private: QFont font; bool pixelSizeSet; bool pointSizeSet; + mutable QDeclarativeNullableValue<int> dpi; }; QT_END_NAMESPACE diff --git a/src/declarative/qml/qdeclarativeworkerscript.cpp b/src/declarative/qml/qdeclarativeworkerscript.cpp index 2ca030e..aec84a6 100644 --- a/src/declarative/qml/qdeclarativeworkerscript.cpp +++ b/src/declarative/qml/qdeclarativeworkerscript.cpp @@ -521,9 +521,9 @@ void QDeclarativeWorkerScriptEngine::run() that the main GUI thread is not blocked. Messages can be passed between the new thread and the parent thread - using sendMessage() and the onMessage() handler. + using \l sendMessage() and the \l {WorkerScript::onMessage}{onMessage()} handler. - Here is an example: + An example: \snippet doc/src/snippets/declarative/workerscript.qml 0 @@ -541,6 +541,9 @@ void QDeclarativeWorkerScriptEngine::run() called, triggering the \tt WorkerScript.onMessage() handler in \tt script.js. This in turn sends a reply message that is then received by the \tt onMessage() handler of \tt myWorker. + + \sa {declarative/threading/workerscript}{WorkerScript example}, + {declarative/threading/threadedlistmodel}{Threaded ListModel example} */ QDeclarativeWorkerScript::QDeclarativeWorkerScript(QObject *parent) : QObject(parent), m_engine(0), m_scriptId(-1), m_componentComplete(true) @@ -555,7 +558,7 @@ QDeclarativeWorkerScript::~QDeclarativeWorkerScript() /*! \qmlproperty url WorkerScript::source - This holds the url of the javascript file that implements the + This holds the url of the JavaScript file that implements the \tt WorkerScript.onMessage() handler for threaded operations. */ QUrl QDeclarativeWorkerScript::source() const @@ -576,7 +579,7 @@ void QDeclarativeWorkerScript::setSource(const QUrl &source) emit sourceChanged(); } -/* +/*! \qmlmethod WorkerScript::sendMessage(jsobject message) Sends the given \a message to a worker script handler in another diff --git a/src/declarative/util/qdeclarativeanimation.cpp b/src/declarative/util/qdeclarativeanimation.cpp index de1c0cb..25cf133 100644 --- a/src/declarative/util/qdeclarativeanimation.cpp +++ b/src/declarative/util/qdeclarativeanimation.cpp @@ -557,6 +557,8 @@ void QDeclarativeAbstractAnimation::timelineComplete() NumberAnimation { ... duration: 200 } } \endcode + + \sa {QML Animation}, {declarative/animation/basics}{Animation basics example} */ /*! \internal @@ -627,6 +629,8 @@ QAbstractAnimation *QDeclarativePauseAnimation::qtAnimation() When used in a transition, ColorAnimation will by default animate all properties of type color that are changing. If a property or properties are explicitly set for the animation, then those will be used instead. + + \sa {QML Animation}, {declarative/animation/basics}{Animation basics example} */ /*! \internal @@ -1082,11 +1086,13 @@ void QDeclarativePropertyAction::transition(QDeclarativeStateActions &actions, \inherits PropertyAnimation \brief The NumberAnimation element allows you to animate changes in properties of type qreal. - Animate a set of properties over 200ms, from their values in the start state to + For example, to animate a set of properties over 200ms, from their values in the start state to their values in the end state of the transition: \code NumberAnimation { properties: "x,y,scale"; duration: 200 } \endcode + + \sa {QML Animation}, {declarative/animation/basics}{Animation basics example} */ /*! @@ -1156,6 +1162,8 @@ void QDeclarativeNumberAnimation::setTo(qreal t) \since 4.7 \inherits PropertyAnimation \brief The Vector3dAnimation element allows you to animate changes in properties of type QVector3d. + + \sa {QML Animation}, {declarative/animation/basics}{Animation basics example} */ /*! @@ -1224,7 +1232,8 @@ void QDeclarativeVector3dAnimation::setTo(QVector3D t) When used in a transition RotationAnimation will rotate all properties named "rotation" or "angle". You can override this by providing - your own properties via \c properties or \c property. + your own properties via \l {PropertyAnimation::properties}{properties} or + \l {PropertyAnimation::property}{property}. In the following example we use RotationAnimation to animate the rotation between states via the shortest path. @@ -1238,6 +1247,8 @@ void QDeclarativeVector3dAnimation::setTo(QVector3D t) RotationAnimation { direction: RotationAnimation.Shortest } } \endqml + + \sa {QML Animation}, {declarative/animation/basics}{Animation basics example} */ /*! @@ -1446,7 +1457,7 @@ QDeclarativeListProperty<QDeclarativeAbstractAnimation> QDeclarativeAnimationGro } \endcode - \sa ParallelAnimation + \sa ParallelAnimation, {QML Animation}, {declarative/animation/basics}{Animation basics example} */ QDeclarativeSequentialAnimation::QDeclarativeSequentialAnimation(QObject *parent) : @@ -1508,7 +1519,7 @@ void QDeclarativeSequentialAnimation::transition(QDeclarativeStateActions &actio } \endcode - \sa SequentialAnimation + \sa SequentialAnimation, {QML Animation}, {declarative/animation/basics}{Animation basics example} */ /*! \internal @@ -1657,6 +1668,8 @@ void QDeclarativePropertyAnimationPrivate::convertVariant(QVariant &variant, int Depending on how the animation is used, the set of properties normally used will be different. For more information see the individual property documentation, as well as the \l{QML Animation} introduction. + + \sa {QML Animation}, {declarative/animation/basics}{Animation basics example} */ QDeclarativePropertyAnimation::QDeclarativePropertyAnimation(QObject *parent) @@ -1761,7 +1774,7 @@ void QDeclarativePropertyAnimation::setTo(const QVariant &t) To specify an easing curve you need to specify at least the type. For some curves you can also specify amplitude, period and/or overshoot (more details provided after the table). The default easing curve is - Linear. + \c Easing.Linear. \qml PropertyAnimation { properties: "y"; easing.type: Easing.InOutElastic; easing.amplitude: 2.0; easing.period: 1.5 } @@ -1938,15 +1951,15 @@ void QDeclarativePropertyAnimation::setTo(const QVariant &t) \o \inlineimage qeasingcurve-outinbounce.png \endtable - easing.amplitude is only applicable for bounce and elastic curves (curves of type - Easing.InBounce, Easing.OutBounce, Easing.InOutBounce, Easing.OutInBounce, Easing.InElastic, - Easing.OutElastic, Easing.InOutElastic or Easing.OutInElastic). + \c easing.amplitude is only applicable for bounce and elastic curves (curves of type + \c Easing.InBounce, \c Easing.OutBounce, \c Easing.InOutBounce, \c Easing.OutInBounce, \c Easing.InElastic, + \c Easing.OutElastic, \c Easing.InOutElastic or \c Easing.OutInElastic). - easing.overshoot is only applicable if type is: Easing.InBack, Easing.OutBack, - Easing.InOutBack or Easing.OutInBack. + \c easing.overshoot is only applicable if \c easing.type is: \c Easing.InBack, \c Easing.OutBack, + \c Easing.InOutBack or \c Easing.OutInBack. - easing.period is only applicable if type is: Easing.InElastic, Easing.OutElastic, - Easing.InOutElastic or Easing.OutInElastic. + \c easing.period is only applicable if easing.type is: \c Easing.InElastic, \c Easing.OutElastic, + \c Easing.InOutElastic or \c Easing.OutInElastic. See the \l {declarative/animation/easing}{easing} example for a demonstration of the different easing settings. @@ -2032,8 +2045,9 @@ void QDeclarativePropertyAnimation::setProperties(const QString &prop) The singular forms are slightly optimized, so if you do have only a single target/property to animate you should try to use them. - In many cases these properties do not need to be explicitly specified -- they can be - inferred from the animation framework. + In many cases these properties do not need to be explicitly specified, as they can be + inferred from the animation framework: + \table 80% \row \o Value Source / Behavior @@ -2119,52 +2133,39 @@ QAbstractAnimation *QDeclarativePropertyAnimation::qtAnimation() return d->va; } -struct PropertyUpdater : public QDeclarativeBulkValueUpdater +void QDeclarativeAnimationPropertyUpdater::setValue(qreal v) { - QDeclarativeStateActions actions; - int interpolatorType; //for Number/ColorAnimation - int prevInterpolatorType; //for generic - QVariantAnimation::Interpolator interpolator; - bool reverse; - bool fromSourced; - bool fromDefined; - bool *wasDeleted; - PropertyUpdater() : prevInterpolatorType(0), wasDeleted(0) {} - ~PropertyUpdater() { if (wasDeleted) *wasDeleted = true; } - void setValue(qreal v) - { - bool deleted = false; - wasDeleted = &deleted; - if (reverse) //QVariantAnimation sends us 1->0 when reversed, but we are expecting 0->1 - v = 1 - v; - for (int ii = 0; ii < actions.count(); ++ii) { - QDeclarativeAction &action = actions[ii]; - - if (v == 1.) - QDeclarativePropertyPrivate::write(action.property, action.toValue, QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding); - else { - if (!fromSourced && !fromDefined) { - action.fromValue = action.property.read(); - if (interpolatorType) - QDeclarativePropertyAnimationPrivate::convertVariant(action.fromValue, interpolatorType); - } - if (!interpolatorType) { - int propType = action.property.propertyType(); - if (!prevInterpolatorType || prevInterpolatorType != propType) { - prevInterpolatorType = propType; - interpolator = QVariantAnimationPrivate::getInterpolator(prevInterpolatorType); - } + bool deleted = false; + wasDeleted = &deleted; + if (reverse) //QVariantAnimation sends us 1->0 when reversed, but we are expecting 0->1 + v = 1 - v; + for (int ii = 0; ii < actions.count(); ++ii) { + QDeclarativeAction &action = actions[ii]; + + if (v == 1.) + QDeclarativePropertyPrivate::write(action.property, action.toValue, QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding); + else { + if (!fromSourced && !fromDefined) { + action.fromValue = action.property.read(); + if (interpolatorType) + QDeclarativePropertyAnimationPrivate::convertVariant(action.fromValue, interpolatorType); + } + if (!interpolatorType) { + int propType = action.property.propertyType(); + if (!prevInterpolatorType || prevInterpolatorType != propType) { + prevInterpolatorType = propType; + interpolator = QVariantAnimationPrivate::getInterpolator(prevInterpolatorType); } - if (interpolator) - QDeclarativePropertyPrivate::write(action.property, interpolator(action.fromValue.constData(), action.toValue.constData(), v), QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding); } - if (deleted) - return; + if (interpolator) + QDeclarativePropertyPrivate::write(action.property, interpolator(action.fromValue.constData(), action.toValue.constData(), v), QDeclarativePropertyPrivate::BypassInterceptor | QDeclarativePropertyPrivate::DontRemoveBinding); } - wasDeleted = 0; - fromSourced = true; + if (deleted) + return; } -}; + wasDeleted = 0; + fromSourced = true; +} void QDeclarativePropertyAnimation::transition(QDeclarativeStateActions &actions, QDeclarativeProperties &modified, @@ -2194,7 +2195,7 @@ void QDeclarativePropertyAnimation::transition(QDeclarativeStateActions &actions props << d->defaultProperties.split(QLatin1Char(',')); } - PropertyUpdater *data = new PropertyUpdater; + QDeclarativeAnimationPropertyUpdater *data = new QDeclarativeAnimationPropertyUpdater; data->interpolatorType = d->interpolatorType; data->interpolator = d->interpolator; data->reverse = direction == Backward ? true : false; @@ -2319,6 +2320,8 @@ void QDeclarativePropertyAnimation::transition(QDeclarativeStateActions &actions When used in a transition, ParentAnimation will by default animate all ParentChanges. + + \sa {QML Animation}, {declarative/animation/basics}{Animation basics example} */ /*! @@ -2771,7 +2774,7 @@ void QDeclarativeAnchorAnimation::transition(QDeclarativeStateActions &actions, { Q_UNUSED(modified); Q_D(QDeclarativeAnchorAnimation); - PropertyUpdater *data = new PropertyUpdater; + QDeclarativeAnimationPropertyUpdater *data = new QDeclarativeAnimationPropertyUpdater; data->interpolatorType = QMetaType::QReal; data->interpolator = d->interpolator; diff --git a/src/declarative/util/qdeclarativeanimation_p.h b/src/declarative/util/qdeclarativeanimation_p.h index e7cd8a8..3f8fbdd 100644 --- a/src/declarative/util/qdeclarativeanimation_p.h +++ b/src/declarative/util/qdeclarativeanimation_p.h @@ -384,7 +384,7 @@ Q_SIGNALS: }; class QDeclarativeAnimationGroupPrivate; -class QDeclarativeAnimationGroup : public QDeclarativeAbstractAnimation +class Q_AUTOTEST_EXPORT QDeclarativeAnimationGroup : public QDeclarativeAbstractAnimation { Q_OBJECT Q_DECLARE_PRIVATE(QDeclarativeAnimationGroup) diff --git a/src/declarative/util/qdeclarativeanimation_p_p.h b/src/declarative/util/qdeclarativeanimation_p_p.h index 3b0f52e..b6d6bbb 100644 --- a/src/declarative/util/qdeclarativeanimation_p_p.h +++ b/src/declarative/util/qdeclarativeanimation_p_p.h @@ -96,7 +96,7 @@ private: }; //performs an action of type QAbstractAnimationAction -class QActionAnimation : public QAbstractAnimation +class Q_AUTOTEST_EXPORT QActionAnimation : public QAbstractAnimation { Q_OBJECT public: @@ -143,7 +143,7 @@ public: }; //animates QDeclarativeBulkValueUpdater (assumes start and end values will be reals or compatible) -class QDeclarativeBulkValueAnimator : public QVariantAnimation +class Q_AUTOTEST_EXPORT QDeclarativeBulkValueAnimator : public QVariantAnimation { Q_OBJECT public: @@ -378,6 +378,22 @@ public: QList<QDeclarativeItem*> targets; }; +class Q_AUTOTEST_EXPORT QDeclarativeAnimationPropertyUpdater : public QDeclarativeBulkValueUpdater +{ +public: + QDeclarativeStateActions actions; + int interpolatorType; //for Number/ColorAnimation + int prevInterpolatorType; //for generic + QVariantAnimation::Interpolator interpolator; + bool reverse; + bool fromSourced; + bool fromDefined; + bool *wasDeleted; + QDeclarativeAnimationPropertyUpdater() : prevInterpolatorType(0), wasDeleted(0) {} + ~QDeclarativeAnimationPropertyUpdater() { if (wasDeleted) *wasDeleted = true; } + void setValue(qreal v); +}; + QT_END_NAMESPACE #endif // QDECLARATIVEANIMATION_P_H diff --git a/src/declarative/util/qdeclarativeconnections.cpp b/src/declarative/util/qdeclarativeconnections.cpp index 808d196..b364821 100644 --- a/src/declarative/util/qdeclarativeconnections.cpp +++ b/src/declarative/util/qdeclarativeconnections.cpp @@ -72,7 +72,9 @@ public: /*! \qmlclass Connections QDeclarativeConnections \since 4.7 - \brief A Connections object describes generalized connections to signals. + \brief A Connections element describes generalized connections to signals. + + A Connections object creates a connection to a QML signal. When connecting to signals in QML, the usual way is to create an "on<Signal>" handler that reacts when a signal is received, like this: @@ -83,16 +85,16 @@ public: } \endqml - However, in some cases, it is not possible to connect to a signal in this - way, such as: + However, it is not possible to connect to a signal in this way in some + cases, such as when: \list - \i multiple connections to the same signal - \i connections outside the scope of the signal sender - \i connections to targets not defined in QML + \i Multiple connections to the same signal are required + \i Creating connections outside the scope of the signal sender + \i Connecting to targets not defined in QML \endlist - When any of these are needed, the Connections object can be used instead. + When any of these are needed, the Connections element can be used instead. For example, the above code can be changed to use a Connections object, like this: @@ -105,7 +107,7 @@ public: } \endqml - More generally, the Connections object can be a child of some other object than + More generally, the Connections object can be a child of some object other than the sender of the signal: \qml @@ -141,7 +143,7 @@ QDeclarativeConnections::~QDeclarativeConnections() \qmlproperty Object Connections::target This property holds the object that sends the signal. - If not set at all, the target defaults to be the parent of the Connections. + If this property is not set, the \c target defaults to the parent of the Connection. If set to null, no connection is made and any signal handlers are ignored until the target is not null. @@ -175,12 +177,11 @@ void QDeclarativeConnections::setTarget(QObject *obj) /*! \qmlproperty bool Connections::ignoreUnknownSignals - Normally, you will get a runtime error if you try to connect - to signals on an object which the object does not have. + Normally, a connection to a non-existent signal produces runtime errors. - By setting this flag to true, such errors are ignored. This is - useful if you intend to connect to different types of object, handling - a different set of signals for each. + If this property is set to \c true, such errors are ignored. + This is useful if you intend to connect to different types of objects, handling + a different set of signals for each object. */ bool QDeclarativeConnections::ignoreUnknownSignals() const { diff --git a/src/declarative/util/qdeclarativefontloader.cpp b/src/declarative/util/qdeclarativefontloader.cpp index c73f827..83bdb17 100644 --- a/src/declarative/util/qdeclarativefontloader.cpp +++ b/src/declarative/util/qdeclarativefontloader.cpp @@ -79,16 +79,27 @@ public: /*! \qmlclass FontLoader QDeclarativeFontLoader \since 4.7 - \brief This item allows using fonts by name or url. + \brief The FontLoader element allows fonts to be loaded by name or URL. - Example: + The FontLoader element is used to load fonts by name or URL. + + The \l status indicates when the font has been loaded, which is useful + for fonts loaded from remote sources. + + For example: \qml - FontLoader { id: fixedFont; name: "Courier" } - FontLoader { id: webFont; source: "http://www.mysite.com/myfont.ttf" } + import Qt 4.7 - Text { text: "Fixed-size font"; font.family: fixedFont.name } - Text { text: "Fancy font"; font.family: webFont.name } + Column { + FontLoader { id: fixedFont; name: "Courier" } + FontLoader { id: webFont; source: "http://www.mysite.com/myfont.ttf" } + + Text { text: "Fixed-size font"; font.family: fixedFont.name } + Text { text: "Fancy font"; font.family: webFont.name } + } \endqml + + \sa {declarative/text/fonts}{Fonts example} */ QDeclarativeFontLoader::QDeclarativeFontLoader(QObject *parent) : QObject(*(new QDeclarativeFontLoaderPrivate), parent) @@ -183,15 +194,26 @@ void QDeclarativeFontLoader::setName(const QString &name) \o FontLoader.Error - an error occurred while loading the font \endlist - Note that a change in the status property does not cause anything to happen - (although it reflects what has happened to the font loader internally). If you wish - to react to the change in status you need to do it yourself, for example in one - of the following ways: - \list - \o Create a state, so that a state change occurs, e.g. State{name: 'loaded'; when: loader.status = FontLoader.Ready;} - \o Do something inside the onStatusChanged signal handler, e.g. FontLoader{id: loader; onStatusChanged: if(loader.status == FontLoader.Ready) console.log('Loaded');} - \o Bind to the status variable somewhere, e.g. Text{text: if(loader.status!=FontLoader.Ready){'Not Loaded';}else{'Loaded';}} - \endlist + Use this status to provide an update or respond to the status change in some way. + For example, you could: + + \e {Trigger a state change:} + \qml + State { name: 'loaded'; when: loader.status = FontLoader.Ready } + \endqml + + \e {Implement an \c onStatusChanged signal handler:} + \qml + FontLoader { + id: loader + onStatusChanged: if (loader.status == FontLoader.Ready) console.log('Loaded') + } + \endqml + + \e {Bind to the status value:} + \qml + Text { text: loader.status != FontLoader.Ready ? 'Not Loaded' : 'Loaded' } + \endqml */ QDeclarativeFontLoader::Status QDeclarativeFontLoader::status() const { diff --git a/src/declarative/util/qdeclarativelistmodel.cpp b/src/declarative/util/qdeclarativelistmodel.cpp index 7518eb7..ff83227 100644 --- a/src/declarative/util/qdeclarativelistmodel.cpp +++ b/src/declarative/util/qdeclarativelistmodel.cpp @@ -76,125 +76,41 @@ QDeclarativeListModelParser::ListInstruction *QDeclarativeListModelParser::ListM For example: - \code - ListModel { - id: fruitModel - ListElement { - name: "Apple" - cost: 2.45 - } - ListElement { - name: "Orange" - cost: 3.25 - } - ListElement { - name: "Banana" - cost: 1.95 - } - } - \endcode + \snippet doc/src/snippets/declarative/listmodel.qml 0 - Roles (properties) must begin with a lower-case letter.The above example defines a + Roles (properties) must begin with a lower-case letter. The above example defines a ListModel containing three elements, with the roles "name" and "cost". Values must be simple constants - either strings (quoted), bools (true, false), numbers, or enum values (like Text.AlignHCenter). The defined model can be used in views such as ListView: - \code - Component { - id: fruitDelegate - Item { - width: 200; height: 50 - Text { text: name } - Text { text: '$'+cost; anchors.right: parent.right } - } - } - ListView { - model: fruitModel - delegate: fruitDelegate - anchors.fill: parent - } - \endcode + \snippet doc/src/snippets/declarative/listmodel-simple.qml 0 + \dots 8 + \snippet doc/src/snippets/declarative/listmodel-simple.qml 1 + \image listmodel.png It is possible for roles to contain list data. In the example below we create a list of fruit attributes: - \code - ListModel { - id: fruitModel - ListElement { - name: "Apple" - cost: 2.45 - attributes: [ - ListElement { description: "Core" }, - ListElement { description: "Deciduous" } - ] - } - ListElement { - name: "Orange" - cost: 3.25 - attributes: [ - ListElement { description: "Citrus" } - ] - } - ListElement { - name: "Banana" - cost: 1.95 - attributes: [ - ListElement { description: "Tropical" }, - ListElement { description: "Seedless" } - ] - } - } - \endcode + \snippet doc/src/snippets/declarative/listmodel-nested.qml model + + The delegate below displays all the fruit attributes: + + \snippet doc/src/snippets/declarative/listmodel-nested.qml delegate + \image listmodel-nested.png - The delegate below will list all the fruit attributes: - \code - Component { - id: fruitDelegate - Item { - width: 200; height: 50 - Text { id: name; text: name } - Text { text: '$'+cost; anchors.right: parent.right } - Row { - anchors.top: name.bottom - spacing: 5 - Text { text: "Attributes:" } - Repeater { - model: attributes - Component { Text { text: description } } - } - } - } - } - \endcode \section2 Modifying list models The content of a ListModel may be created and modified using the clear(), - append(), and set() methods. For example: - - \code - Component { - id: fruitDelegate - Item { - width: 200; height: 50 - Text { text: name } - Text { text: '$'+cost; anchors.right: parent.right } - - // Double the price when clicked. - MouseArea { - anchors.fill: parent - onClicked: fruitModel.set(index, "cost", cost*2) - } - } - } - \endcode + append(), set() and setProperty() methods. For example: + + \snippet doc/src/snippets/declarative/listmodel-modify.qml delegate When creating content dynamically, note that the set of available properties cannot be changed - except by first clearing the model - whatever properties are first added are then the - only permitted properties in the model. + except by first clearing the model. Whatever properties are first added to the model are then the + only permitted properties in the model until it is cleared. \section2 Using threaded list models with WorkerScript @@ -214,11 +130,11 @@ QDeclarativeListModelParser::ListInstruction *QDeclarativeListModelParser::ListM \snippet examples/declarative/threading/threadedlistmodel/dataloader.js 0 The application's \tt Timer object periodically sends a message to the - worker script by calling \tt WorkerScript::sendMessage(). When this message - is received, \tt WorkerScript.onMessage() is invoked in + worker script by calling \l WorkerScript::sendMessage(). When this message + is received, \l {WorkerScript::onMessage}{WorkerScript.onMessage()} is invoked in \tt dataloader.js, which appends the current time to the list model. - Note the call to sync() from the \c WorkerScript.onMessage() handler. + Note the call to sync() from the \l {WorkerScript::onMessage}{WorkerScript.onMessage()} handler. You must call sync() or else the changes made to the list from the external thread will not be reflected in the list model in the main thread. @@ -244,7 +160,7 @@ QDeclarativeListModelParser::ListInstruction *QDeclarativeListModelParser::ListM In addition, the WorkerScript cannot add any list data to the model. - \sa {qmlmodels}{Data Models}, WorkerScript, QtDeclarative + \sa {qmlmodels}{Data Models}, {declarative/threading/threadedlistmodel}{Threaded ListModel example}, QtDeclarative */ @@ -454,7 +370,7 @@ void QDeclarativeListModel::insert(int index, const QScriptValue& valuemap) to the end of the list: \code - fruitModel.move(0,fruitModel.count-3,3) + fruitModel.move(0, fruitModel.count - 3, 3) \endcode \sa append() diff --git a/src/declarative/util/qdeclarativepackage.cpp b/src/declarative/util/qdeclarativepackage.cpp index 9617b86..b149120 100644 --- a/src/declarative/util/qdeclarativepackage.cpp +++ b/src/declarative/util/qdeclarativepackage.cpp @@ -48,17 +48,17 @@ QT_BEGIN_NAMESPACE /*! \qmlclass Package QDeclarativePackage - \brief Package provides a collection of named items + \brief Package provides a collection of named items. - The Package class is currently used in conjunction with + The Package class is used in conjunction with VisualDataModel to enable delegates with a shared context to be provided to multiple views. Any item within a Package may be assigned a name via the - \e {Package.name} attached property. + \l{Package::name}{Package.name} attached property. The example below creates a Package containing two named items; - \e list and \e grid. The third element in the package is parented to whichever + \e list and \e grid. The third element in the package (the \l Rectangle) is parented to whichever delegate it should appear in. This allows an item to move between views. @@ -70,7 +70,12 @@ QT_BEGIN_NAMESPACE \snippet examples/declarative/modelviews/package/view.qml 0 - \sa QtDeclarative + \sa {declarative/modelviews/package}{Package example}, QtDeclarative +*/ + +/*! + \qmlattachedproperty bool Package::name + This attached property holds the name of an item within a Package. */ diff --git a/src/declarative/util/qdeclarativepackage_p.h b/src/declarative/util/qdeclarativepackage_p.h index 87d9b80..6b12ef7 100644 --- a/src/declarative/util/qdeclarativepackage_p.h +++ b/src/declarative/util/qdeclarativepackage_p.h @@ -50,15 +50,9 @@ QT_BEGIN_NAMESPACE QT_MODULE(Declarative) -/***************************************************************************** - ***************************************************************************** - XXX Experimental - ***************************************************************************** -*****************************************************************************/ - class QDeclarativePackagePrivate; class QDeclarativePackageAttached; -class QDeclarativePackage : public QObject +class Q_AUTOTEST_EXPORT QDeclarativePackage : public QObject { Q_OBJECT Q_DECLARE_PRIVATE(QDeclarativePackage) diff --git a/src/declarative/util/qdeclarativepropertychanges.cpp b/src/declarative/util/qdeclarativepropertychanges.cpp index d99de7a..8e3ec82 100644 --- a/src/declarative/util/qdeclarativepropertychanges.cpp +++ b/src/declarative/util/qdeclarativepropertychanges.cpp @@ -62,11 +62,11 @@ QT_BEGIN_NAMESPACE /*! \qmlclass PropertyChanges QDeclarativePropertyChanges \since 4.7 - \brief The PropertyChanges element describes new property values for a state. + \brief The PropertyChanges element describes new property bindings or values for a state. PropertyChanges provides a state change that modifies the properties of an item. - Here is a property change that modifies the text and color of a Text element + Here is a property change that modifies the text and color of a \l Text element when it is clicked: \qml @@ -89,6 +89,21 @@ QT_BEGIN_NAMESPACE MouseArea { anchors.fill: parent; onClicked: myText.state = 'myState' } } \endqml + + By default, PropertyChanges will establish new bindings where appropriate. + For example, the following creates a new binding for myItem's \c height property. + + \qml + PropertyChanges { + target: myItem + height: parent.height + } + \endqml + + If you don't want a binding to be established (and instead just want to assign + the value of the binding at the time the state is entered), + you should set the PropertyChange's \l{PropertyChanges::explicit}{explicit} + property to \c true. State-specific script for signal handlers can also be specified: @@ -485,8 +500,8 @@ QDeclarativePropertyChanges::ActionList QDeclarativePropertyChanges::actions() If explicit is set to true, any potential bindings will be interpreted as once-off assignments that occur when the state is entered. - In the following example, the addition of explicit prevents myItem.width from - being bound to parent.width. Instead, it is assigned the value of parent.width + In the following example, the addition of explicit prevents \c myItem.width from + being bound to \c parent.width. Instead, it is assigned the value of \c parent.width at the time of the state change. \qml PropertyChanges { diff --git a/src/declarative/util/qdeclarativesmoothedanimation.cpp b/src/declarative/util/qdeclarativesmoothedanimation.cpp index bd48ef0..6b6df4d 100644 --- a/src/declarative/util/qdeclarativesmoothedanimation.cpp +++ b/src/declarative/util/qdeclarativesmoothedanimation.cpp @@ -307,7 +307,7 @@ Rectangle { set to a value such as 0.5 units/second. Animating from 0 to 1.0 with a velocity of 0.5 will take 2000 ms to complete. - \sa SpringFollow + \sa SpringFollow, {QML Animation}, {declarative/animation/basics}{Animation basics example} */ QDeclarativeSmoothedAnimation::QDeclarativeSmoothedAnimation(QObject *parent) diff --git a/src/declarative/util/qdeclarativesmoothedanimation_p_p.h b/src/declarative/util/qdeclarativesmoothedanimation_p_p.h index 81cd229..8cdbea2 100644 --- a/src/declarative/util/qdeclarativesmoothedanimation_p_p.h +++ b/src/declarative/util/qdeclarativesmoothedanimation_p_p.h @@ -65,7 +65,7 @@ QT_BEGIN_NAMESPACE -class QSmoothedAnimation : public QAbstractAnimation +class Q_AUTOTEST_EXPORT QSmoothedAnimation : public QAbstractAnimation { public: QSmoothedAnimation(QObject *parent=0); diff --git a/src/declarative/util/qdeclarativestate.cpp b/src/declarative/util/qdeclarativestate.cpp index dc2b2cc..ae19a9c 100644 --- a/src/declarative/util/qdeclarativestate.cpp +++ b/src/declarative/util/qdeclarativestate.cpp @@ -136,12 +136,31 @@ QDeclarativeStateOperation::QDeclarativeStateOperation(QObjectPrivate &dd, QObje \since 4.7 \brief The State element defines configurations of objects and properties. - A state is specified as a set of batched changes from the default configuration. + A \e state is a set of batched changes from the default configuration. + + All items have a default state that defines the default configuration of objects + and property values. New states can be defined by adding State items to the \l {Item::states}{states} property to + allow items to switch between different configurations. These configurations + can, for example, be used to apply different sets of property values or execute + different scripts. + + The following example displays a single Rectangle. In the default state, the rectangle + is colored black. In the "clicked" state, a PropertyChanges element changes the + rectangle's color to red. Clicking within the MouseArea toggles the rectangle's state + between the default state and the "clicked" state, thus toggling the color of the + rectangle between black and red. + + \snippet doc/src/snippets/declarative/state.qml 0 + + Notice the default state is referred to using an empty string (""). + + States are commonly used together with \l {state-transitions}{Transitions} to provide + animations when state changes occur. \note setting the state of an object from within another state of the same object is not allowed. - \sa {qmlstates}{States}, {state-transitions}{Transitions}, QtDeclarative + \sa {declarative/animation/states}{states example}, {qmlstates}{States}, {state-transitions}{Transitions}, QtDeclarative */ /*! @@ -173,7 +192,7 @@ QDeclarativeState::~QDeclarativeState() /*! \qmlproperty string State::name - This property holds the name of the state + This property holds the name of the state. Each state should have a unique name. */ @@ -187,6 +206,13 @@ void QDeclarativeState::setName(const QString &n) { Q_D(QDeclarativeState); d->name = n; + d->named = true; +} + +bool QDeclarativeState::isNamed() const +{ + Q_D(const QDeclarativeState); + return d->named; } bool QDeclarativeState::isWhenKnown() const @@ -197,12 +223,12 @@ bool QDeclarativeState::isWhenKnown() const /*! \qmlproperty bool State::when - This property holds when the state should be applied + This property holds when the state should be applied. - This should be set to an expression that evaluates to true when you want the state to + This should be set to an expression that evaluates to \c true when you want the state to be applied. - If multiple states in a group have \c when clauses that evaluate to true at the same time, + If multiple states in a group have \c when clauses that evaluate to \c true at the same time, the first matching state will be applied. For example, in the following snippet \c state1 will always be selected rather than \c state2 when sharedCondition becomes \c true. @@ -229,7 +255,9 @@ void QDeclarativeState::setWhen(QDeclarativeBinding *when) /*! \qmlproperty string State::extend - This property holds the state that this state extends + This property holds the state that this state extends. + + When a state extends another state, it inherits all the changes of that state. The state being extended is treated as the base state in regards to the changes specified by the extending state. diff --git a/src/declarative/util/qdeclarativestate_p.h b/src/declarative/util/qdeclarativestate_p.h index 25715c6..2e2ce7b 100644 --- a/src/declarative/util/qdeclarativestate_p.h +++ b/src/declarative/util/qdeclarativestate_p.h @@ -84,7 +84,7 @@ public: void deleteFromBinding(); }; -class QDeclarativeActionEvent +class Q_AUTOTEST_EXPORT QDeclarativeActionEvent { public: virtual ~QDeclarativeActionEvent(); @@ -146,6 +146,7 @@ public: QString name() const; void setName(const QString &); + bool isNamed() const; /*'when' is a QDeclarativeBinding to limit state changes oscillation due to the unpredictable order of evaluation of bound expressions*/ diff --git a/src/declarative/util/qdeclarativestate_p_p.h b/src/declarative/util/qdeclarativestate_p_p.h index 4a2af0f..2ef9bb0 100644 --- a/src/declarative/util/qdeclarativestate_p_p.h +++ b/src/declarative/util/qdeclarativestate_p_p.h @@ -101,12 +101,13 @@ class QDeclarativeStatePrivate : public QObjectPrivate public: QDeclarativeStatePrivate() - : when(0), inState(false), group(0) {} + : when(0), named(false), inState(false), group(0) {} typedef QList<QDeclarativeSimpleAction> SimpleActionList; QString name; QDeclarativeBinding *when; + bool named; struct OperationGuard : public QDeclarativeGuard<QDeclarativeStateOperation> { diff --git a/src/declarative/util/qdeclarativestategroup.cpp b/src/declarative/util/qdeclarativestategroup.cpp index 9b042d7..67cd12e 100644 --- a/src/declarative/util/qdeclarativestategroup.cpp +++ b/src/declarative/util/qdeclarativestategroup.cpp @@ -91,8 +91,8 @@ public: \since 4.7 \brief The StateGroup element provides state support for non-Item elements. - Item (and all dervied elements) provides built in support for states and transitions - via its state, states and transitions properties. StateGroup provides an easy way to + Item (and all derived elements) provides built in support for states and transitions + via its \l{Item::state}{state}, \l{Item::states}{states} and \l{Item::transitions}{transitions} properties. StateGroup provides an easy way to use this support in other (non-Item-derived) elements. \qml @@ -263,7 +263,7 @@ void QDeclarativeStateGroup::componentComplete() for (int ii = 0; ii < d->states.count(); ++ii) { QDeclarativeState *state = d->states.at(ii); - if (state->name().isEmpty()) + if (!state->isNamed()) state->setName(QLatin1String("anonymousState") % QString::number(++d->unnamedCount)); } @@ -295,7 +295,7 @@ bool QDeclarativeStateGroupPrivate::updateAutoState() for (int ii = 0; ii < states.count(); ++ii) { QDeclarativeState *state = states.at(ii); if (state->isWhenKnown()) { - if (!state->name().isEmpty()) { + if (state->isNamed()) { if (state->when() && state->when()->evaluate().toBool()) { if (stateChangeDebug()) qWarning() << "Setting auto state due to:" diff --git a/src/declarative/util/qdeclarativestateoperations.cpp b/src/declarative/util/qdeclarativestateoperations.cpp index 99f163e..51e6f99 100644 --- a/src/declarative/util/qdeclarativestateoperations.cpp +++ b/src/declarative/util/qdeclarativestateoperations.cpp @@ -172,6 +172,14 @@ void QDeclarativeParentChangePrivate::doChange(QDeclarativeItem *targetParent, Q items involved in the reparenting (i.e. items in the common ancestor tree for the original and new parent). + The example below displays a large red rectangle and a small blue rectangle, side by side. + When the \c blueRect is clicked, it changes to the "reparented" state: its parent is changed to \c redRect and it is + positioned at (10, 10) within the red rectangle, as specified in the ParentChange. + + \snippet doc/src/snippets/declarative/parentchange.qml 0 + + \image parentchange.png + You can specify at which point in a transition you want a ParentChange to occur by using a ParentAnimation. */ @@ -583,9 +591,9 @@ public: \qmlclass StateChangeScript QDeclarativeStateChangeScript \brief The StateChangeScript element allows you to run a script in a state. - StateChangeScripts are run when entering the state. You can use - ScriptAction to specify at which point in the transition - you want the StateChangeScript to be run. + A StateChangeScript is run upon entering a state. You can optionally use + ScriptAction to specify the point in the transition at which + the StateChangeScript should to be run. \qml State { @@ -687,22 +695,18 @@ QString QDeclarativeStateChangeScript::typeName() const \qmlclass AnchorChanges QDeclarativeAnchorChanges \brief The AnchorChanges element allows you to change the anchors of an item in a state. - In the following example we change the top and bottom anchors of an item: - \qml - State { - name: "reanchored" - AnchorChanges { - target: content; - anchors.top: window.top; - anchors.bottom: window.bottom - } - PropertyChanges { - target: content; - anchors.topMargin: 3 - anchors.bottomMargin: 3; - } - } - \endqml + The AnchorChanges element is used to modify the anchors of an item in a \l State. + + AnchorChanges cannot be used to modify the margins on an item. For this, use + PropertyChanges intead. + + In the following example we change the top and bottom anchors of an item + using AnchorChanges, and the top and bottom anchor margins using + PropertyChanges: + + \snippet doc/src/snippets/declarative/anchorchanges.qml 0 + + \image anchorchanges.png AnchorChanges can be animated using AnchorAnimation. \qml diff --git a/src/declarative/util/qdeclarativesystempalette.cpp b/src/declarative/util/qdeclarativesystempalette.cpp index 6c62446..c334859 100644 --- a/src/declarative/util/qdeclarativesystempalette.cpp +++ b/src/declarative/util/qdeclarativesystempalette.cpp @@ -59,22 +59,25 @@ public: /*! \qmlclass SystemPalette QDeclarativeSystemPalette \since 4.7 - \brief The SystemPalette item gives access to the Qt palettes. - \sa QPalette + \brief The SystemPalette element provides access to the Qt palettes. - Example: - \qml - SystemPalette { id: myPalette; colorGroup: Qt.Active } + The SystemPalette element provides access to the Qt application + palettes. This provides information about the standard colors used + for application windows, buttons and other features. These colors + are grouped into three \e {color groups}: \c Active, \c Inactive, + and \c Disabled. See the QPalette documentation for details about + color groups and the properties provided by SystemPalette. - Rectangle { - width: 640; height: 480 - color: myPalette.window - Text { - anchors.fill: parent - text: "Hello!"; color: myPalette.windowText - } - } - \endqml + This can be used to color items in a way that provides a more + native look and feel. + + The following example creates a palette from the \c Active color + group and uses this to color the window and text items + appropriately: + + \snippet doc/src/snippets/declarative/systempalette.qml 0 + + \sa QPalette */ QDeclarativeSystemPalette::QDeclarativeSystemPalette(QObject *parent) : QObject(*(new QDeclarativeSystemPalettePrivate), parent) @@ -258,10 +261,15 @@ QColor QDeclarativeSystemPalette::highlightedText() const } /*! - \qmlproperty QDeclarativeSystemPalette::ColorGroup SystemPalette::colorGroup + \qmlproperty enumeration SystemPalette::colorGroup + + The color group of the palette. This can be one of: - The color group of the palette. It can be Active, Inactive or Disabled. - Active is the default. + \list + \o SystemPalette.Active (default) + \o SystemPalette.Inactive + \o SystemPalette.Disabled + \endlist \sa QPalette::ColorGroup */ diff --git a/src/declarative/util/qdeclarativetimeline_p_p.h b/src/declarative/util/qdeclarativetimeline_p_p.h index 598c897..61f6bcd 100644 --- a/src/declarative/util/qdeclarativetimeline_p_p.h +++ b/src/declarative/util/qdeclarativetimeline_p_p.h @@ -63,7 +63,7 @@ class QDeclarativeTimeLineValue; class QDeclarativeTimeLineCallback; struct QDeclarativeTimeLinePrivate; class QDeclarativeTimeLineObject; -class QDeclarativeTimeLine : public QAbstractAnimation +class Q_AUTOTEST_EXPORT QDeclarativeTimeLine : public QAbstractAnimation { Q_OBJECT public: @@ -117,7 +117,7 @@ private: QDeclarativeTimeLinePrivate *d; }; -class QDeclarativeTimeLineObject +class Q_AUTOTEST_EXPORT QDeclarativeTimeLineObject { public: QDeclarativeTimeLineObject(); @@ -129,7 +129,7 @@ protected: QDeclarativeTimeLine *_t; }; -class QDeclarativeTimeLineValue : public QDeclarativeTimeLineObject +class Q_AUTOTEST_EXPORT QDeclarativeTimeLineValue : public QDeclarativeTimeLineObject { public: QDeclarativeTimeLineValue(qreal v = 0.) : _v(v) {} @@ -147,7 +147,7 @@ private: qreal _v; }; -class QDeclarativeTimeLineCallback +class Q_AUTOTEST_EXPORT QDeclarativeTimeLineCallback { public: typedef void (*Callback)(void *); diff --git a/src/declarative/util/qdeclarativetimer.cpp b/src/declarative/util/qdeclarativetimer.cpp index 53a9d83..9e18eb5 100644 --- a/src/declarative/util/qdeclarativetimer.cpp +++ b/src/declarative/util/qdeclarativetimer.cpp @@ -80,17 +80,22 @@ public: the text every 500 milliseconds: \qml - Timer { - interval: 500; running: true; repeat: true - onTriggered: time.text = Date().toString() - } - Text { - id: time + import Qt 4.7 + + Item { + Timer { + interval: 500; running: true; repeat: true + onTriggered: time.text = Date().toString() + } + + Text { + id: time + } } \endqml - QDeclarativeTimer is synchronized with the animation timer. Since the animation - timer is usually set to 60fps, the resolution of QDeclarativeTimer will be + The Timer element is synchronized with the animation timer. Since the animation + timer is usually set to 60fps, the resolution of Timer will be at best 16ms. If the Timer is running and one of its properties is changed, the @@ -98,8 +103,6 @@ public: 1000ms has its \e repeat property changed 500ms after starting, the elapsed time will be reset to 0, and the Timer will be triggered 1000ms later. - - \sa {QtDeclarative} */ QDeclarativeTimer::QDeclarativeTimer(QObject *parent) diff --git a/src/declarative/util/qdeclarativetransitionmanager_p_p.h b/src/declarative/util/qdeclarativetransitionmanager_p_p.h index 2e23898..75d11a9 100644 --- a/src/declarative/util/qdeclarativetransitionmanager_p_p.h +++ b/src/declarative/util/qdeclarativetransitionmanager_p_p.h @@ -59,7 +59,7 @@ QT_BEGIN_NAMESPACE class QDeclarativeStatePrivate; class QDeclarativeTransitionManagerPrivate; -class QDeclarativeTransitionManager +class Q_AUTOTEST_EXPORT QDeclarativeTransitionManager { public: QDeclarativeTransitionManager(); diff --git a/src/declarative/util/qdeclarativeview.cpp b/src/declarative/util/qdeclarativeview.cpp index 6059ad6..0414e65 100644 --- a/src/declarative/util/qdeclarativeview.cpp +++ b/src/declarative/util/qdeclarativeview.cpp @@ -131,7 +131,7 @@ class QDeclarativeViewPrivate : public QGraphicsViewPrivate, public QDeclarative Q_DECLARE_PUBLIC(QDeclarativeView) public: QDeclarativeViewPrivate() - : root(0), declarativeItemRoot(0), graphicsWidgetRoot(0), component(0), resizeMode(QDeclarativeView::SizeViewToRootObject) {} + : root(0), declarativeItemRoot(0), graphicsWidgetRoot(0), component(0), resizeMode(QDeclarativeView::SizeViewToRootObject), initialSize(0,0) {} ~QDeclarativeViewPrivate() { delete root; } void execute(); void itemGeometryChanged(QDeclarativeItem *item, const QRectF &newGeometry, const QRectF &oldGeometry); @@ -150,6 +150,7 @@ public: QBasicTimer resizetimer; QDeclarativeView::ResizeMode resizeMode; + QSize initialSize; QElapsedTimer frameTimer; void init(); @@ -586,9 +587,11 @@ void QDeclarativeView::setRootObject(QObject *obj) } if (d->root) { - QSize initialSize = d->rootObjectSize(); - if (initialSize != size()) { - resize(initialSize); + d->initialSize = d->rootObjectSize(); + if (d->initialSize != size()) { + if (!(parentWidget() && parentWidget()->layout())) { + resize(d->initialSize); + } } d->initResize(); } @@ -638,6 +641,15 @@ QSize QDeclarativeView::sizeHint() const } /*! + Returns the initial size of the root object +*/ +QSize QDeclarativeView::initialSize() const +{ + Q_D(const QDeclarativeView); + return d->initialSize; +} + +/*! Returns the view's root \l {QGraphicsObject} {item}. */ QGraphicsObject *QDeclarativeView::rootObject() const diff --git a/src/declarative/util/qdeclarativeview.h b/src/declarative/util/qdeclarativeview.h index e9cff32..cdcf134 100644 --- a/src/declarative/util/qdeclarativeview.h +++ b/src/declarative/util/qdeclarativeview.h @@ -90,6 +90,7 @@ public: QList<QDeclarativeError> errors() const; QSize sizeHint() const; + QSize initialSize() const; Q_SIGNALS: void sceneResized(QSize size); // ??? diff --git a/src/declarative/util/qdeclarativexmllistmodel.cpp b/src/declarative/util/qdeclarativexmllistmodel.cpp index 4f9355b..4adef25 100644 --- a/src/declarative/util/qdeclarativexmllistmodel.cpp +++ b/src/declarative/util/qdeclarativexmllistmodel.cpp @@ -523,10 +523,13 @@ void QDeclarativeXmlListModelPrivate::clear_role(QDeclarativeListProperty<QDecla A XmlListModel could create a model from this data, like this: \qml + import Qt 4.7 + XmlListModel { id: xmlModel source: "http://www.mysite.com/feed.xml" query: "/rss/channel/item" + XmlRole { name: "title"; query: "title/string()" } XmlRole { name: "pubDate"; query: "pubDate/string()" } } @@ -536,7 +539,7 @@ void QDeclarativeXmlListModelPrivate::clear_role(QDeclarativeListProperty<QDecla a model item for each \c <item> in the XML document. The XmlRole objects define the - model item attributes; here, each model item will have \c title and \c pubDate + model item attributes. Here, each model item will have \c title and \c pubDate attributes that match the \c title and \c pubDate values of its corresponding \c <item>. (See \l XmlRole::query for more examples of valid XPath expressions for XmlRole.) @@ -672,11 +675,11 @@ void QDeclarativeXmlListModel::setSource(const QUrl &src) /*! \qmlproperty string XmlListModel::xml - This property holds XML text set directly. + This property holds the XML data for this model, if set. The text is assumed to be UTF-8 encoded. - If both source and xml are set, xml will be used. + If both \l source and \c xml are set, \c xml will be used. */ QString QDeclarativeXmlListModel::xml() const { @@ -733,6 +736,7 @@ void QDeclarativeXmlListModel::setQuery(const QString &query) source: "http://mysite.com/feed.xml" query: "/feed/entry" namespaceDeclarations: "declare default element namespace 'http://www.w3.org/2005/Atom';" + XmlRole { name: "title"; query: "title/string()" } } \endqml diff --git a/src/declarative/3rdparty/qlistmodelinterface.cpp b/src/declarative/util/qlistmodelinterface.cpp index 98d6a5b..98d6a5b 100644 --- a/src/declarative/3rdparty/qlistmodelinterface.cpp +++ b/src/declarative/util/qlistmodelinterface.cpp diff --git a/src/declarative/3rdparty/qlistmodelinterface_p.h b/src/declarative/util/qlistmodelinterface_p.h index 07592ad..07592ad 100644 --- a/src/declarative/3rdparty/qlistmodelinterface_p.h +++ b/src/declarative/util/qlistmodelinterface_p.h diff --git a/src/declarative/util/util.pri b/src/declarative/util/util.pri index f20bba1..04cfc68 100644 --- a/src/declarative/util/util.pri +++ b/src/declarative/util/util.pri @@ -27,7 +27,8 @@ SOURCES += \ $$PWD/qdeclarativebehavior.cpp \ $$PWD/qdeclarativefontloader.cpp \ $$PWD/qdeclarativestyledtext.cpp \ - $$PWD/qdeclarativelistmodelworkeragent.cpp + $$PWD/qdeclarativelistmodelworkeragent.cpp \ + $$PWD/qlistmodelinterface.cpp HEADERS += \ $$PWD/qdeclarativeutilmodule_p.h\ @@ -61,7 +62,8 @@ HEADERS += \ $$PWD/qdeclarativebehavior_p.h \ $$PWD/qdeclarativefontloader_p.h \ $$PWD/qdeclarativestyledtext_p.h \ - $$PWD/qdeclarativelistmodelworkeragent_p.h + $$PWD/qdeclarativelistmodelworkeragent_p.h \ + $$PWD/qlistmodelinterface_p.h contains(QT_CONFIG, xmlpatterns) { QT+=xmlpatterns |