diff options
author | Gabriel de Dietrich <gabriel.dietrich-de@nokia.com> | 2012-08-17 13:23:19 +0200 |
---|---|---|
committer | Qt by Nokia <qt-info@nokia.com> | 2012-08-20 12:20:55 +0200 |
commit | 806dda08d685bc5f9ed71dfe8b61f21848d48066 (patch) | |
tree | a63533a1c4a335ae17adc105abb0ae4e62e2f26e /examples/widgets/graphicsview | |
parent | 9f942014e31842b512c3198de035d041c59f54a9 (diff) |
Moving .qdoc files under examples/widgets/doc
Updated those .qdoc files to refer to the new relative examples
emplacement. Images and snippets to be moved later.
Also grouped all widgets related examples under widgets.
Change-Id: Ib29696e2d8948524537f53e8dda88f9ee26a597f
Reviewed-by: J-P Nurmi <j-p.nurmi@nokia.com>
Diffstat (limited to 'examples/widgets/graphicsview')
175 files changed, 13006 insertions, 0 deletions
diff --git a/examples/widgets/graphicsview/README b/examples/widgets/graphicsview/README new file mode 100644 index 0000000000..e710fc3c13 --- /dev/null +++ b/examples/widgets/graphicsview/README @@ -0,0 +1,9 @@ +Qt is provided with a comprehensive canvas through the GraphicsView +classes. + +These examples demonstrate the fundamental aspects of canvas programming +with Qt. + + +Documentation for these examples can be found via the Examples +link in the main Qt documentation. diff --git a/examples/widgets/graphicsview/anchorlayout/anchorlayout.desktop b/examples/widgets/graphicsview/anchorlayout/anchorlayout.desktop new file mode 100644 index 0000000000..6cf53c3f9b --- /dev/null +++ b/examples/widgets/graphicsview/anchorlayout/anchorlayout.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Anchor Layout +Exec=/opt/usr/bin/anchorlayout +Icon=anchorlayout +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/graphicsview/anchorlayout/anchorlayout.pro b/examples/widgets/graphicsview/anchorlayout/anchorlayout.pro new file mode 100644 index 0000000000..7b18a621db --- /dev/null +++ b/examples/widgets/graphicsview/anchorlayout/anchorlayout.pro @@ -0,0 +1,13 @@ +SOURCES = main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/anchorlayout +sources.files = $$SOURCES $$HEADERS $$RESOURCES anchorlayout.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/anchorlayout +INSTALLS += target sources + +TARGET = anchorlayout +QT += widgets + + +simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/graphicsview/anchorlayout/main.cpp b/examples/widgets/graphicsview/anchorlayout/main.cpp new file mode 100644 index 0000000000..839aef2e39 --- /dev/null +++ b/examples/widgets/graphicsview/anchorlayout/main.cpp @@ -0,0 +1,129 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QGraphicsWidget> +#include <QGraphicsProxyWidget> +#include <QGraphicsAnchorLayout> +#include <QtWidgets> + +static QGraphicsProxyWidget *createItem(const QSizeF &minimum = QSizeF(100.0, 100.0), + const QSizeF &preferred = QSize(150.0, 100.0), + const QSizeF &maximum = QSizeF(200.0, 100.0), + const QString &name = "0") +{ + QGraphicsProxyWidget *w = new QGraphicsProxyWidget; + w->setWidget(new QPushButton(name)); + w->setData(0, name); + w->setMinimumSize(minimum); + w->setPreferredSize(preferred); + w->setMaximumSize(maximum); + + w->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + return w; +} + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + QGraphicsScene scene; + scene.setSceneRect(0, 0, 800, 480); + + QSizeF minSize(30, 100); + QSizeF prefSize(210, 100); + QSizeF maxSize(300, 100); + + QGraphicsProxyWidget *a = createItem(minSize, prefSize, maxSize, "A"); + QGraphicsProxyWidget *b = createItem(minSize, prefSize, maxSize, "B"); + QGraphicsProxyWidget *c = createItem(minSize, prefSize, maxSize, "C"); + QGraphicsProxyWidget *d = createItem(minSize, prefSize, maxSize, "D"); + QGraphicsProxyWidget *e = createItem(minSize, prefSize, maxSize, "E"); + QGraphicsProxyWidget *f = createItem(QSizeF(30, 50), QSizeF(150, 50), maxSize, "F (overflow)"); + QGraphicsProxyWidget *g = createItem(QSizeF(30, 50), QSizeF(30, 100), maxSize, "G (overflow)"); + + QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout; + l->setSpacing(0); + + QGraphicsWidget *w = new QGraphicsWidget(0, Qt::Window); + w->setPos(20, 20); + w->setLayout(l); + + // vertical + l->addAnchor(a, Qt::AnchorTop, l, Qt::AnchorTop); + l->addAnchor(b, Qt::AnchorTop, l, Qt::AnchorTop); + + l->addAnchor(c, Qt::AnchorTop, a, Qt::AnchorBottom); + l->addAnchor(c, Qt::AnchorTop, b, Qt::AnchorBottom); + l->addAnchor(c, Qt::AnchorBottom, d, Qt::AnchorTop); + l->addAnchor(c, Qt::AnchorBottom, e, Qt::AnchorTop); + + l->addAnchor(d, Qt::AnchorBottom, l, Qt::AnchorBottom); + l->addAnchor(e, Qt::AnchorBottom, l, Qt::AnchorBottom); + + l->addAnchor(c, Qt::AnchorTop, f, Qt::AnchorTop); + l->addAnchor(c, Qt::AnchorVerticalCenter, f, Qt::AnchorBottom); + l->addAnchor(f, Qt::AnchorBottom, g, Qt::AnchorTop); + l->addAnchor(c, Qt::AnchorBottom, g, Qt::AnchorBottom); + + // horizontal + l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft); + l->addAnchor(l, Qt::AnchorLeft, d, Qt::AnchorLeft); + l->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorLeft); + + l->addAnchor(a, Qt::AnchorRight, c, Qt::AnchorLeft); + l->addAnchor(c, Qt::AnchorRight, e, Qt::AnchorLeft); + + l->addAnchor(b, Qt::AnchorRight, l, Qt::AnchorRight); + l->addAnchor(e, Qt::AnchorRight, l, Qt::AnchorRight); + l->addAnchor(d, Qt::AnchorRight, e, Qt::AnchorLeft); + + l->addAnchor(l, Qt::AnchorLeft, f, Qt::AnchorLeft); + l->addAnchor(l, Qt::AnchorLeft, g, Qt::AnchorLeft); + l->addAnchor(f, Qt::AnchorRight, g, Qt::AnchorRight); + + + scene.addItem(w); + scene.setBackgroundBrush(Qt::darkGreen); + QGraphicsView view(&scene); + + view.show(); + + return app.exec(); +} diff --git a/examples/widgets/graphicsview/basicgraphicslayouts/basicgraphicslayouts.desktop b/examples/widgets/graphicsview/basicgraphicslayouts/basicgraphicslayouts.desktop new file mode 100644 index 0000000000..be1c3e4a84 --- /dev/null +++ b/examples/widgets/graphicsview/basicgraphicslayouts/basicgraphicslayouts.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Basic Graphics Layouts +Exec=/opt/usr/bin/basicgraphicslayouts +Icon=basicgraphicslayouts +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/graphicsview/basicgraphicslayouts/basicgraphicslayouts.pro b/examples/widgets/graphicsview/basicgraphicslayouts/basicgraphicslayouts.pro new file mode 100644 index 0000000000..202c8d87a0 --- /dev/null +++ b/examples/widgets/graphicsview/basicgraphicslayouts/basicgraphicslayouts.pro @@ -0,0 +1,14 @@ +HEADERS = layoutitem.h \ + window.h +SOURCES = layoutitem.cpp \ + main.cpp \ + window.cpp +RESOURCES = basicgraphicslayouts.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/basicgraphicslayouts +sources.files = $$SOURCES $$HEADERS $$RESOURCES basicgraphicslayouts.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/basicgraphicslayouts +INSTALLS += target sources + +QT += widgets diff --git a/examples/widgets/graphicsview/basicgraphicslayouts/basicgraphicslayouts.qrc b/examples/widgets/graphicsview/basicgraphicslayouts/basicgraphicslayouts.qrc new file mode 100644 index 0000000000..fbe2efa572 --- /dev/null +++ b/examples/widgets/graphicsview/basicgraphicslayouts/basicgraphicslayouts.qrc @@ -0,0 +1,5 @@ +<RCC> + <qresource> + <file>images/block.png</file> + </qresource> +</RCC> diff --git a/examples/widgets/graphicsview/basicgraphicslayouts/images/block.png b/examples/widgets/graphicsview/basicgraphicslayouts/images/block.png Binary files differnew file mode 100644 index 0000000000..4c72a3f508 --- /dev/null +++ b/examples/widgets/graphicsview/basicgraphicslayouts/images/block.png diff --git a/examples/widgets/graphicsview/basicgraphicslayouts/layoutitem.cpp b/examples/widgets/graphicsview/basicgraphicslayouts/layoutitem.cpp new file mode 100644 index 0000000000..7067cddece --- /dev/null +++ b/examples/widgets/graphicsview/basicgraphicslayouts/layoutitem.cpp @@ -0,0 +1,130 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "layoutitem.h" + +//! [0] +LayoutItem::LayoutItem(QGraphicsItem *parent/* = 0*/) + : QGraphicsLayoutItem(), QGraphicsItem(parent) +{ + m_pix = new QPixmap(QLatin1String(":/images/block.png")); + setGraphicsItem(this); +} +//! [0] + +LayoutItem::~LayoutItem() +{ + delete m_pix; +} + +//! [1] +void LayoutItem::paint(QPainter *painter, + const QStyleOptionGraphicsItem *option, QWidget *widget /*= 0*/) +{ + Q_UNUSED(widget); + Q_UNUSED(option); + + QRectF frame(QPointF(0,0), geometry().size()); + qreal w = m_pix->width(); + qreal h = m_pix->height(); + QGradientStops stops; +//! [1] + +//! [2] + // paint a background rect (with gradient) + QLinearGradient gradient(frame.topLeft(), frame.topLeft() + QPointF(200,200)); + stops << QGradientStop(0.0, QColor(60, 60, 60)); + stops << QGradientStop(frame.height()/2/frame.height(), QColor(102, 176, 54)); + + //stops << QGradientStop(((frame.height() + h)/2 )/frame.height(), QColor(157, 195, 55)); + stops << QGradientStop(1.0, QColor(215, 215, 215)); + gradient.setStops(stops); + painter->setBrush(QBrush(gradient)); + painter->drawRoundedRect(frame, 10.0, 10.0); + + // paint a rect around the pixmap (with gradient) + QPointF pixpos = frame.center() - (QPointF(w, h)/2); + QRectF innerFrame(pixpos, QSizeF(w, h)); + innerFrame.adjust(-4, -4, +4, +4); + gradient.setStart(innerFrame.topLeft()); + gradient.setFinalStop(innerFrame.bottomRight()); + stops.clear(); + stops << QGradientStop(0.0, QColor(215, 255, 200)); + stops << QGradientStop(0.5, QColor(102, 176, 54)); + stops << QGradientStop(1.0, QColor(0, 0, 0)); + gradient.setStops(stops); + painter->setBrush(QBrush(gradient)); + painter->drawRoundedRect(innerFrame, 10.0, 10.0); + painter->drawPixmap(pixpos, *m_pix); +} +//! [2] + +//! [3] +QRectF LayoutItem::boundingRect() const +{ + return QRectF(QPointF(0,0), geometry().size()); +} +//! [3] + +//! [4] +void LayoutItem::setGeometry(const QRectF &geom) +{ + prepareGeometryChange(); + QGraphicsLayoutItem::setGeometry(geom); + setPos(geom.topLeft()); +} +//! [4] + +//! [5] +QSizeF LayoutItem::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const +{ + switch (which) { + case Qt::MinimumSize: + case Qt::PreferredSize: + // Do not allow a size smaller than the pixmap with two frames around it. + return m_pix->size() + QSize(12, 12); + case Qt::MaximumSize: + return QSizeF(1000,1000); + default: + break; + } + return constraint; +} +//! [5] diff --git a/examples/widgets/graphicsview/basicgraphicslayouts/layoutitem.h b/examples/widgets/graphicsview/basicgraphicslayouts/layoutitem.h new file mode 100644 index 0000000000..798c4650c6 --- /dev/null +++ b/examples/widgets/graphicsview/basicgraphicslayouts/layoutitem.h @@ -0,0 +1,65 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef LAYOUTITEM_H +#define LAYOUTITEM_H +#include <QtWidgets> + +//! [0] +class LayoutItem : public QGraphicsLayoutItem, public QGraphicsItem +{ +public: + LayoutItem(QGraphicsItem *parent = 0); + ~LayoutItem(); + // Inherited from QGraphicsLayoutItem + void setGeometry(const QRectF &geom); + QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const; + + // Inherited from QGraphicsItem + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, + QWidget *widget = 0); + +private: + QPixmap *m_pix; +}; +//! [0] + +#endif diff --git a/examples/widgets/graphicsview/basicgraphicslayouts/main.cpp b/examples/widgets/graphicsview/basicgraphicslayouts/main.cpp new file mode 100644 index 0000000000..ef482235a9 --- /dev/null +++ b/examples/widgets/graphicsview/basicgraphicslayouts/main.cpp @@ -0,0 +1,58 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> + +#include "window.h" + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + QGraphicsScene scene; + + Window *window = new Window; + scene.addItem(window); + QGraphicsView view(&scene); + view.resize(600, 600); + view.show(); + + return app.exec(); +} diff --git a/examples/widgets/graphicsview/basicgraphicslayouts/window.cpp b/examples/widgets/graphicsview/basicgraphicslayouts/window.cpp new file mode 100644 index 0000000000..e3786b61f1 --- /dev/null +++ b/examples/widgets/graphicsview/basicgraphicslayouts/window.cpp @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "window.h" +#include "layoutitem.h" + +Window::Window(QGraphicsWidget *parent) : QGraphicsWidget(parent, Qt::Window) +{ +//! [0] + QGraphicsLinearLayout *windowLayout = new QGraphicsLinearLayout(Qt::Vertical); + QGraphicsLinearLayout *linear = new QGraphicsLinearLayout(windowLayout); + LayoutItem *item = new LayoutItem; + linear->addItem(item); + linear->setStretchFactor(item, 1); +//! [0] + +//! [1] + item = new LayoutItem; + linear->addItem(item); + linear->setStretchFactor(item, 3); + windowLayout->addItem(linear); +//! [1] + +//! [2] + QGraphicsGridLayout *grid = new QGraphicsGridLayout(windowLayout); + item = new LayoutItem; + grid->addItem(item, 0, 0, 4, 1); + item = new LayoutItem; + item->setMaximumHeight(item->minimumHeight()); + grid->addItem(item, 0, 1, 2, 1, Qt::AlignVCenter); + item = new LayoutItem; + item->setMaximumHeight(item->minimumHeight()); + grid->addItem(item, 2, 1, 2, 1, Qt::AlignVCenter); + item = new LayoutItem; + grid->addItem(item, 0, 2); + item = new LayoutItem; + grid->addItem(item, 1, 2); + item = new LayoutItem; + grid->addItem(item, 2, 2); + item = new LayoutItem; + grid->addItem(item, 3, 2); + windowLayout->addItem(grid); +//! [2] + +//! [3] + setLayout(windowLayout); + setWindowTitle(tr("Basic Graphics Layouts Example")); +//! [3] + +} + + + diff --git a/examples/widgets/graphicsview/basicgraphicslayouts/window.h b/examples/widgets/graphicsview/basicgraphicslayouts/window.h new file mode 100644 index 0000000000..5c1cc2ed4f --- /dev/null +++ b/examples/widgets/graphicsview/basicgraphicslayouts/window.h @@ -0,0 +1,57 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef WINDOW_H +#define WINDOW_H + +#include <QtWidgets/QGraphicsWidget> + +//! [0] +class Window : public QGraphicsWidget { + Q_OBJECT + +public: + Window(QGraphicsWidget *parent = 0); + +}; +//! [0] + +#endif //WINDOW_H + diff --git a/examples/widgets/graphicsview/boxes/3rdparty/fbm.c b/examples/widgets/graphicsview/boxes/3rdparty/fbm.c new file mode 100644 index 0000000000..98eb87a33b --- /dev/null +++ b/examples/widgets/graphicsview/boxes/3rdparty/fbm.c @@ -0,0 +1,207 @@ +/***************************************************************** + + Implementation of the fractional Brownian motion algorithm. These + functions were originally the work of F. Kenton Musgrave. + For documentation of the different functions please refer to the + book: + "Texturing and modeling: a procedural approach" + by David S. Ebert et. al. + +******************************************************************/ + +#if defined (_MSC_VER) +#include <qglobal.h> +#endif + +#include <time.h> +#include <stdlib.h> +#include "fbm.h" + +#if defined(Q_CC_MSVC) +#pragma warning(disable:4244) +#endif + +/* Definitions used by the noise2() functions */ + +//#define B 0x100 +//#define BM 0xff +#define B 0x20 +#define BM 0x1f + +#define N 0x1000 +#define NP 12 /* 2^N */ +#define NM 0xfff + +static int p[B + B + 2]; +static float g3[B + B + 2][3]; +static float g2[B + B + 2][2]; +static float g1[B + B + 2]; +static int start = 1; + +static void init(void); + +#define s_curve(t) ( t * t * (3. - 2. * t) ) + +#define lerp(t, a, b) ( a + t * (b - a) ) + +#define setup(i,b0,b1,r0,r1)\ + t = vec[i] + N;\ + b0 = ((int)t) & BM;\ + b1 = (b0+1) & BM;\ + r0 = t - (int)t;\ + r1 = r0 - 1.; +#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] ) + +/* Fractional Brownian Motion function */ + +double fBm( Vector point, double H, double lacunarity, double octaves, + int init ) +{ + + double value, frequency, remainder; + int i; + static double exponent_array[10]; + float vec[3]; + + /* precompute and store spectral weights */ + if ( init ) { + start = 1; + srand( time(0) ); + /* seize required memory for exponent_array */ + frequency = 1.0; + for (i=0; i<=octaves; i++) { + /* compute weight for each frequency */ + exponent_array[i] = pow( frequency, -H ); + frequency *= lacunarity; + } + } + + value = 0.0; /* initialize vars to proper values */ + frequency = 1.0; + vec[0]=point.x; + vec[1]=point.y; + vec[2]=point.z; + + + /* inner loop of spectral construction */ + for (i=0; i<octaves; i++) { + /* value += noise3( vec ) * exponent_array[i];*/ + value += noise3( vec ) * exponent_array[i]; + vec[0] *= lacunarity; + vec[1] *= lacunarity; + vec[2] *= lacunarity; + } /* for */ + + remainder = octaves - (int)octaves; + if ( remainder ) /* add in ``octaves'' remainder */ + /* ``i'' and spatial freq. are preset in loop above */ + value += remainder * noise3( vec ) * exponent_array[i]; + + return( value ); + +} /* fBm() */ + + +float noise3(float vec[3]) +{ + int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11; + float rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v; + register int i, j; + + if (start) { + start = 0; + init(); + } + + setup(0, bx0,bx1, rx0,rx1); + setup(1, by0,by1, ry0,ry1); + setup(2, bz0,bz1, rz0,rz1); + + i = p[ bx0 ]; + j = p[ bx1 ]; + + b00 = p[ i + by0 ]; + b10 = p[ j + by0 ]; + b01 = p[ i + by1 ]; + b11 = p[ j + by1 ]; + + t = s_curve(rx0); + sy = s_curve(ry0); + sz = s_curve(rz0); + + + q = g3[ b00 + bz0 ] ; u = at3(rx0,ry0,rz0); + q = g3[ b10 + bz0 ] ; v = at3(rx1,ry0,rz0); + a = lerp(t, u, v); + + q = g3[ b01 + bz0 ] ; u = at3(rx0,ry1,rz0); + q = g3[ b11 + bz0 ] ; v = at3(rx1,ry1,rz0); + b = lerp(t, u, v); + + c = lerp(sy, a, b); + + q = g3[ b00 + bz1 ] ; u = at3(rx0,ry0,rz1); + q = g3[ b10 + bz1 ] ; v = at3(rx1,ry0,rz1); + a = lerp(t, u, v); + + q = g3[ b01 + bz1 ] ; u = at3(rx0,ry1,rz1); + q = g3[ b11 + bz1 ] ; v = at3(rx1,ry1,rz1); + b = lerp(t, u, v); + + d = lerp(sy, a, b); + + return lerp(sz, c, d); +} + +static void normalize2(float v[2]) +{ + float s; + + s = sqrt(v[0] * v[0] + v[1] * v[1]); + v[0] = v[0] / s; + v[1] = v[1] / s; +} + +static void normalize3(float v[3]) +{ + float s; + + s = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); + v[0] = v[0] / s; + v[1] = v[1] / s; + v[2] = v[2] / s; +} + +static void init(void) +{ + int i, j, k; + + for (i = 0 ; i < B ; i++) { + p[i] = i; + + g1[i] = (float)((rand() % (B + B)) - B) / B; + + for (j = 0 ; j < 2 ; j++) + g2[i][j] = (float)((rand() % (B + B)) - B) / B; + normalize2(g2[i]); + + for (j = 0 ; j < 3 ; j++) + g3[i][j] = (float)((rand() % (B + B)) - B) / B; + normalize3(g3[i]); + } + + while (--i) { + k = p[i]; + p[i] = p[j = rand() % B]; + p[j] = k; + } + + for (i = 0 ; i < B + 2 ; i++) { + p[B + i] = p[i]; + g1[B + i] = g1[i]; + for (j = 0 ; j < 2 ; j++) + g2[B + i][j] = g2[i][j]; + for (j = 0 ; j < 3 ; j++) + g3[B + i][j] = g3[i][j]; + } +} diff --git a/examples/widgets/graphicsview/boxes/3rdparty/fbm.h b/examples/widgets/graphicsview/boxes/3rdparty/fbm.h new file mode 100644 index 0000000000..b8a4a99ae4 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/3rdparty/fbm.h @@ -0,0 +1,40 @@ +/***************************************************************** + + Prototypes for the fractional Brownian motion algorithm. These + functions were originally the work of F. Kenton Musgrave. For + documentation of the different functions please refer to the book: + "Texturing and modeling: a procedural approach" + by David S. Ebert et. al. + +******************************************************************/ + +#ifndef _fbm_h +#define _fbm_h + +#include <math.h> + +#ifdef __cplusplus +extern "C" { +#endif + +//#define TRUE 1 +//#define FALSE 0 + +typedef struct { + double x; + double y; + double z; +} Vector; + +float noise3(float vec[]); +double fBm( Vector point, double H, double lacunarity, double octaves, + int init ); +#endif + +#ifdef __cplusplus +} +#endif + + + + diff --git a/examples/widgets/graphicsview/boxes/basic.fsh b/examples/widgets/graphicsview/boxes/basic.fsh new file mode 100644 index 0000000000..917dbbaa0b --- /dev/null +++ b/examples/widgets/graphicsview/boxes/basic.fsh @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform vec4 basicColor; + +void main() +{ + vec3 N = normalize(normal); + // assume directional light + + gl_MaterialParameters M = gl_FrontMaterial; + + float NdotL = dot(N, lightDirection.xyz); + float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); + + vec3 absN = abs(gl_TexCoord[1].xyz); + vec3 texCoord; + if (absN.x > absN.y && absN.x > absN.z) + texCoord = gl_TexCoord[1].yzx; + else if (absN.y > absN.z) + texCoord = gl_TexCoord[1].zxy; + else + texCoord = gl_TexCoord[1].xyz; + texCoord.y *= -sign(texCoord.z); + texCoord += 0.5; + + vec4 texColor = texture2D(tex, texCoord.xy); + vec4 unlitColor = gl_Color * mix(basicColor, vec4(texColor.xyz, 1.0), texColor.w); + gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + + M.specular * specular * pow(max(RdotL, 0.0), M.shininess); +} diff --git a/examples/widgets/graphicsview/boxes/basic.vsh b/examples/widgets/graphicsview/boxes/basic.vsh new file mode 100644 index 0000000000..db34a1a0d3 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/basic.vsh @@ -0,0 +1,61 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform mat4 view; + +void main() +{ + gl_TexCoord[0] = gl_MultiTexCoord0; + gl_TexCoord[1] = gl_Vertex; + specular = gl_LightSource[0].specular; + ambient = gl_LightSource[0].ambient; + diffuse = gl_LightSource[0].diffuse; + lightDirection = view * gl_LightSource[0].position; + + normal = gl_NormalMatrix * gl_Normal; + position = (gl_ModelViewMatrix * gl_Vertex).xyz; + + gl_FrontColor = gl_Color; + gl_Position = ftransform(); +} diff --git a/examples/widgets/graphicsview/boxes/boxes.pro b/examples/widgets/graphicsview/boxes/boxes.pro new file mode 100644 index 0000000000..0564ae0ba6 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/boxes.pro @@ -0,0 +1,39 @@ +QT += opengl widgets + +HEADERS += 3rdparty/fbm.h \ + glbuffers.h \ + glextensions.h \ + gltrianglemesh.h \ + qtbox.h \ + roundedbox.h \ + scene.h \ + trackball.h +SOURCES += 3rdparty/fbm.c \ + glbuffers.cpp \ + glextensions.cpp \ + main.cpp \ + qtbox.cpp \ + roundedbox.cpp \ + scene.cpp \ + trackball.cpp + +RESOURCES += boxes.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/boxes +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.html *.jpg *.png *.fsh *.vsh *.par +sources.files -= 3rdparty/fbm.h 3rdparty/fbm.c +sources.files += 3rdparty +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/boxes +INSTALLS += target sources + +wince*: { + DEPLOYMENT_PLUGIN += qjpeg +} + +win32-msvc* { + QMAKE_CXXFLAGS -= -Zm200 + QMAKE_CFLAGS -= -Zm200 + QMAKE_CXXFLAGS += -Zm500 + QMAKE_CFLAGS += -Zm500 +} diff --git a/examples/widgets/graphicsview/boxes/boxes.qrc b/examples/widgets/graphicsview/boxes/boxes.qrc new file mode 100644 index 0000000000..d27506dc5a --- /dev/null +++ b/examples/widgets/graphicsview/boxes/boxes.qrc @@ -0,0 +1,25 @@ +<!DOCTYPE RCC><RCC version="1.0"> +<qresource prefix="/res/boxes"> + <file>cubemap_negx.jpg</file> + <file>cubemap_negy.jpg</file> + <file>cubemap_negz.jpg</file> + <file>cubemap_posx.jpg</file> + <file>cubemap_posy.jpg</file> + <file>cubemap_posz.jpg</file> + <file>square.jpg</file> + <file>basic.vsh</file> + <file>basic.fsh</file> + <file>dotted.fsh</file> + <file>fresnel.fsh</file> + <file>glass.fsh</file> + <file>granite.fsh</file> + <file>marble.fsh</file> + <file>reflection.fsh</file> + <file>refraction.fsh</file> + <file>wood.fsh</file> + <file>parameters.par</file> + <file>qt-logo.png</file> + <file>smiley.png</file> + <file>qt-logo.jpg</file> +</qresource> +</RCC> diff --git a/examples/widgets/graphicsview/boxes/cubemap_negx.jpg b/examples/widgets/graphicsview/boxes/cubemap_negx.jpg Binary files differnew file mode 100644 index 0000000000..07c282eab9 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/cubemap_negx.jpg diff --git a/examples/widgets/graphicsview/boxes/cubemap_negy.jpg b/examples/widgets/graphicsview/boxes/cubemap_negy.jpg Binary files differnew file mode 100644 index 0000000000..46cd2f9cf3 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/cubemap_negy.jpg diff --git a/examples/widgets/graphicsview/boxes/cubemap_negz.jpg b/examples/widgets/graphicsview/boxes/cubemap_negz.jpg Binary files differnew file mode 100644 index 0000000000..40c01ddff3 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/cubemap_negz.jpg diff --git a/examples/widgets/graphicsview/boxes/cubemap_posx.jpg b/examples/widgets/graphicsview/boxes/cubemap_posx.jpg Binary files differnew file mode 100644 index 0000000000..0b42e8a1b1 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/cubemap_posx.jpg diff --git a/examples/widgets/graphicsview/boxes/cubemap_posy.jpg b/examples/widgets/graphicsview/boxes/cubemap_posy.jpg Binary files differnew file mode 100644 index 0000000000..2aca9b1e98 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/cubemap_posy.jpg diff --git a/examples/widgets/graphicsview/boxes/cubemap_posz.jpg b/examples/widgets/graphicsview/boxes/cubemap_posz.jpg Binary files differnew file mode 100644 index 0000000000..2e49173848 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/cubemap_posz.jpg diff --git a/examples/widgets/graphicsview/boxes/dotted.fsh b/examples/widgets/graphicsview/boxes/dotted.fsh new file mode 100644 index 0000000000..2fe32b3b89 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/dotted.fsh @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; + +void main() +{ + vec3 N = normalize(normal); + + gl_MaterialParameters M = gl_FrontMaterial; + + // assume directional light + float NdotL = dot(N, lightDirection.xyz); + float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); + + float r1 = length(fract(7.0 * gl_TexCoord[1].xyz) - 0.5); + float r2 = length(fract(5.0 * gl_TexCoord[1].xyz + 0.2) - 0.5); + float r3 = length(fract(11.0 * gl_TexCoord[1].xyz + 0.7) - 0.5); + vec4 rs = vec4(r1, r2, r3, 0.0); + + vec4 unlitColor = gl_Color * (0.8 - clamp(10.0 * (0.4 - rs), 0.0, 0.2)); + unlitColor.w = 1.0; + gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + + M.specular * specular * pow(max(RdotL, 0.0), M.shininess); +} diff --git a/examples/widgets/graphicsview/boxes/fresnel.fsh b/examples/widgets/graphicsview/boxes/fresnel.fsh new file mode 100644 index 0000000000..8750dd9f20 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/fresnel.fsh @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform samplerCube env; +uniform mat4 view; +uniform vec4 basicColor; + +void main() +{ + vec3 N = normalize(normal); + // assume directional light + + gl_MaterialParameters M = gl_FrontMaterial; + + float NdotL = dot(N, lightDirection.xyz); + float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); + + vec3 absN = abs(gl_TexCoord[1].xyz); + vec3 texCoord; + if (absN.x > absN.y && absN.x > absN.z) + texCoord = gl_TexCoord[1].yzx; + else if (absN.y > absN.z) + texCoord = gl_TexCoord[1].zxy; + else + texCoord = gl_TexCoord[1].xyz; + texCoord.y *= -sign(texCoord.z); + texCoord += 0.5; + + vec4 texColor = texture2D(tex, texCoord.xy); + vec4 unlitColor = gl_Color * mix(basicColor, vec4(texColor.xyz, 1.0), texColor.w); + vec4 litColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + + M.specular * specular * pow(max(RdotL, 0.0), M.shininess); + + vec3 R = 2.0 * dot(-position, N) * N + position; + vec4 reflectedColor = textureCube(env, R * mat3(view[0].xyz, view[1].xyz, view[2].xyz)); + gl_FragColor = mix(litColor, reflectedColor, 0.2 + 0.8 * pow(1.0 + dot(N, normalize(position)), 2.0)); +} diff --git a/examples/widgets/graphicsview/boxes/glass.fsh b/examples/widgets/graphicsview/boxes/glass.fsh new file mode 100644 index 0000000000..d635b2cdc3 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/glass.fsh @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform samplerCube env; +uniform mat4 view; + +// Some arbitrary values +// Arrays don't work here on glsl < 120, apparently. +//const float coeffs[6] = float[6](1.0/4.0, 1.0/4.1, 1.0/4.2, 1.0/4.3, 1.0/4.4, 1.0/4.5); +float coeffs(int i) +{ + return 1.0 / (3.0 + 0.1 * float(i)); +} + +void main() +{ + vec3 N = normalize(normal); + vec3 I = -normalize(position); + mat3 V = mat3(view[0].xyz, view[1].xyz, view[2].xyz); + float IdotN = dot(I, N); + float scales[6]; + vec3 C[6]; + for (int i = 0; i < 6; ++i) { + scales[i] = (IdotN - sqrt(1.0 - coeffs(i) + coeffs(i) * (IdotN * IdotN))); + C[i] = textureCube(env, (-I + coeffs(i) * N) * V).xyz; + } + vec4 refractedColor = 0.25 * vec4(C[5].x + 2.0*C[0].x + C[1].x, C[1].y + 2.0*C[2].y + C[3].y, + C[3].z + 2.0*C[4].z + C[5].z, 4.0); + + vec3 R = 2.0 * dot(-position, N) * N + position; + vec4 reflectedColor = textureCube(env, R * V); + + gl_FragColor = mix(refractedColor, reflectedColor, 0.4 + 0.6 * pow(1.0 - IdotN, 2.0)); +} diff --git a/examples/widgets/graphicsview/boxes/glbuffers.cpp b/examples/widgets/graphicsview/boxes/glbuffers.cpp new file mode 100644 index 0000000000..e2aa2a4789 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/glbuffers.cpp @@ -0,0 +1,402 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "glbuffers.h" +#include <QtGui/qmatrix4x4.h> + + +void qgluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar) +{ + const GLdouble ymax = zNear * tan(fovy * M_PI / 360.0); + const GLdouble ymin = -ymax; + const GLdouble xmin = ymin * aspect; + const GLdouble xmax = ymax * aspect; + glFrustum(xmin, xmax, ymin, ymax, zNear, zFar); +} + +//============================================================================// +// GLTexture // +//============================================================================// + +GLTexture::GLTexture() : m_texture(0), m_failed(false) +{ + glGenTextures(1, &m_texture); +} + +GLTexture::~GLTexture() +{ + glDeleteTextures(1, &m_texture); +} + +//============================================================================// +// GLTexture2D // +//============================================================================// + +GLTexture2D::GLTexture2D(int width, int height) +{ + glBindTexture(GL_TEXTURE_2D, m_texture); + glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, + GL_BGRA, GL_UNSIGNED_BYTE, 0); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + //glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); + glBindTexture(GL_TEXTURE_2D, 0); +} + + +GLTexture2D::GLTexture2D(const QString& fileName, int width, int height) +{ + // TODO: Add error handling. + QImage image(fileName); + + if (image.isNull()) { + m_failed = true; + return; + } + + image = image.convertToFormat(QImage::Format_ARGB32); + + //qDebug() << "Image size:" << image.width() << "x" << image.height(); + if (width <= 0) + width = image.width(); + if (height <= 0) + height = image.height(); + if (width != image.width() || height != image.height()) + image = image.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + + glBindTexture(GL_TEXTURE_2D, m_texture); + + // Works on x86, so probably works on all little-endian systems. + // Does it work on big-endian systems? + glTexImage2D(GL_TEXTURE_2D, 0, 4, image.width(), image.height(), 0, + GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + //glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); + glBindTexture(GL_TEXTURE_2D, 0); +} + +void GLTexture2D::load(int width, int height, QRgb *data) +{ + glBindTexture(GL_TEXTURE_2D, m_texture); + glTexImage2D(GL_TEXTURE_2D, 0, 4, width, height, 0, + GL_BGRA, GL_UNSIGNED_BYTE, data); + glBindTexture(GL_TEXTURE_2D, 0); +} + +void GLTexture2D::bind() +{ + glBindTexture(GL_TEXTURE_2D, m_texture); + glEnable(GL_TEXTURE_2D); +} + +void GLTexture2D::unbind() +{ + glBindTexture(GL_TEXTURE_2D, 0); + glDisable(GL_TEXTURE_2D); +} + + +//============================================================================// +// GLTexture3D // +//============================================================================// + +GLTexture3D::GLTexture3D(int width, int height, int depth) +{ + GLBUFFERS_ASSERT_OPENGL("GLTexture3D::GLTexture3D", glTexImage3D, return) + + glBindTexture(GL_TEXTURE_3D, m_texture); + glTexImage3D(GL_TEXTURE_3D, 0, 4, width, height, depth, 0, + GL_BGRA, GL_UNSIGNED_BYTE, 0); + + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + //glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + //glTexParameteri(GL_TEXTURE_3D, GL_GENERATE_MIPMAP, GL_TRUE); + glBindTexture(GL_TEXTURE_3D, 0); +} + +void GLTexture3D::load(int width, int height, int depth, QRgb *data) +{ + GLBUFFERS_ASSERT_OPENGL("GLTexture3D::load", glTexImage3D, return) + + glBindTexture(GL_TEXTURE_3D, m_texture); + glTexImage3D(GL_TEXTURE_3D, 0, 4, width, height, depth, 0, + GL_BGRA, GL_UNSIGNED_BYTE, data); + glBindTexture(GL_TEXTURE_3D, 0); +} + +void GLTexture3D::bind() +{ + glBindTexture(GL_TEXTURE_3D, m_texture); + glEnable(GL_TEXTURE_3D); +} + +void GLTexture3D::unbind() +{ + glBindTexture(GL_TEXTURE_3D, 0); + glDisable(GL_TEXTURE_3D); +} + +//============================================================================// +// GLTextureCube // +//============================================================================// + +GLTextureCube::GLTextureCube(int size) +{ + glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); + + for (int i = 0; i < 6; ++i) + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 4, size, size, 0, + GL_BGRA, GL_UNSIGNED_BYTE, 0); + + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP, GL_TRUE); + glBindTexture(GL_TEXTURE_CUBE_MAP, 0); +} + +GLTextureCube::GLTextureCube(const QStringList& fileNames, int size) +{ + // TODO: Add error handling. + + glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); + + int index = 0; + foreach (QString file, fileNames) { + QImage image(file); + if (image.isNull()) { + m_failed = true; + break; + } + + image = image.convertToFormat(QImage::Format_ARGB32); + + //qDebug() << "Image size:" << image.width() << "x" << image.height(); + if (size <= 0) + size = image.width(); + if (size != image.width() || size != image.height()) + image = image.scaled(size, size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); + + // Works on x86, so probably works on all little-endian systems. + // Does it work on big-endian systems? + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + index, 0, 4, image.width(), image.height(), 0, + GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); + + if (++index == 6) + break; + } + + // Clear remaining faces. + while (index < 6) { + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + index, 0, 4, size, size, 0, + GL_BGRA, GL_UNSIGNED_BYTE, 0); + ++index; + } + + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + //glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_GENERATE_MIPMAP, GL_TRUE); + glBindTexture(GL_TEXTURE_CUBE_MAP, 0); +} + +void GLTextureCube::load(int size, int face, QRgb *data) +{ + glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); + glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, 4, size, size, 0, + GL_BGRA, GL_UNSIGNED_BYTE, data); + glBindTexture(GL_TEXTURE_CUBE_MAP, 0); +} + +void GLTextureCube::bind() +{ + glBindTexture(GL_TEXTURE_CUBE_MAP, m_texture); + glEnable(GL_TEXTURE_CUBE_MAP); +} + +void GLTextureCube::unbind() +{ + glBindTexture(GL_TEXTURE_CUBE_MAP, 0); + glDisable(GL_TEXTURE_CUBE_MAP); +} + +//============================================================================// +// GLFrameBufferObject // +//============================================================================// + +GLFrameBufferObject::GLFrameBufferObject(int width, int height) + : m_fbo(0) + , m_depthBuffer(0) + , m_width(width) + , m_height(height) + , m_failed(false) +{ + GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::GLFrameBufferObject", + glGenFramebuffersEXT && glGenRenderbuffersEXT && glBindRenderbufferEXT && glRenderbufferStorageEXT, return) + + // TODO: share depth buffers of same size + glGenFramebuffersEXT(1, &m_fbo); + //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); + glGenRenderbuffersEXT(1, &m_depthBuffer); + glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, m_depthBuffer); + glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, m_width, m_height); + //glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_depthBuffer); + //glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); +} + +GLFrameBufferObject::~GLFrameBufferObject() +{ + GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::~GLFrameBufferObject", + glDeleteFramebuffersEXT && glDeleteRenderbuffersEXT, return) + + glDeleteFramebuffersEXT(1, &m_fbo); + glDeleteRenderbuffersEXT(1, &m_depthBuffer); +} + +void GLFrameBufferObject::setAsRenderTarget(bool state) +{ + GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::setAsRenderTarget", glBindFramebufferEXT, return) + + if (state) { + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fbo); + glPushAttrib(GL_VIEWPORT_BIT); + glViewport(0, 0, m_width, m_height); + } else { + glPopAttrib(); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); + } +} + +bool GLFrameBufferObject::isComplete() +{ + GLBUFFERS_ASSERT_OPENGL("GLFrameBufferObject::isComplete", glCheckFramebufferStatusEXT, return false) + + return GL_FRAMEBUFFER_COMPLETE_EXT == glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); +} + +//============================================================================// +// GLRenderTargetCube // +//============================================================================// + +GLRenderTargetCube::GLRenderTargetCube(int size) + : GLTextureCube(size) + , m_fbo(size, size) +{ +} + +void GLRenderTargetCube::begin(int face) +{ + GLBUFFERS_ASSERT_OPENGL("GLRenderTargetCube::begin", + glFramebufferTexture2DEXT && glFramebufferRenderbufferEXT, return) + + m_fbo.setAsRenderTarget(true); + glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, + GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, m_texture, 0); + glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, m_fbo.m_depthBuffer); +} + +void GLRenderTargetCube::end() +{ + m_fbo.setAsRenderTarget(false); +} + +void GLRenderTargetCube::getViewMatrix(QMatrix4x4& mat, int face) +{ + if (face < 0 || face >= 6) { + qWarning("GLRenderTargetCube::getViewMatrix: 'face' must be in the range [0, 6). (face == %d)", face); + return; + } + + static int perm[6][3] = { + {2, 1, 0}, + {2, 1, 0}, + {0, 2, 1}, + {0, 2, 1}, + {0, 1, 2}, + {0, 1, 2}, + }; + + static float signs[6][3] = { + {-1.0f, -1.0f, -1.0f}, + {+1.0f, -1.0f, +1.0f}, + {+1.0f, +1.0f, -1.0f}, + {+1.0f, -1.0f, +1.0f}, + {+1.0f, -1.0f, -1.0f}, + {-1.0f, -1.0f, +1.0f}, + }; + + mat.fill(0.0f); + for (int i = 0; i < 3; ++i) + mat(i, perm[face][i]) = signs[face][i]; + mat(3, 3) = 1.0f; +} + +void GLRenderTargetCube::getProjectionMatrix(QMatrix4x4& mat, float nearZ, float farZ) +{ + static const QMatrix4x4 reference( + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 0.0f, -1.0f, 0.0f); + + mat = reference; + mat(2, 2) = (nearZ+farZ)/(nearZ-farZ); + mat(2, 3) = 2.0f*nearZ*farZ/(nearZ-farZ); +} diff --git a/examples/widgets/graphicsview/boxes/glbuffers.h b/examples/widgets/graphicsview/boxes/glbuffers.h new file mode 100644 index 0000000000..2b91915e8e --- /dev/null +++ b/examples/widgets/graphicsview/boxes/glbuffers.h @@ -0,0 +1,366 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef GLBUFFERS_H +#define GLBUFFERS_H + +//#include <GL/glew.h> +#include "glextensions.h" + +#include <QtWidgets> +#include <QtOpenGL> + +#define BUFFER_OFFSET(i) ((char*)0 + (i)) +#define SIZE_OF_MEMBER(cls, member) sizeof(static_cast<cls *>(0)->member) + +#define GLBUFFERS_ASSERT_OPENGL(prefix, assertion, returnStatement) \ +if (m_failed || !(assertion)) { \ + if (!m_failed) qCritical(prefix ": The necessary OpenGL functions are not available."); \ + m_failed = true; \ + returnStatement; \ +} + +void qgluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar); + +QT_BEGIN_NAMESPACE +class QMatrix4x4; +QT_END_NAMESPACE + +class GLTexture +{ +public: + GLTexture(); + virtual ~GLTexture(); + virtual void bind() = 0; + virtual void unbind() = 0; + virtual bool failed() const {return m_failed;} +protected: + GLuint m_texture; + bool m_failed; +}; + +class GLFrameBufferObject +{ +public: + friend class GLRenderTargetCube; + // friend class GLRenderTarget2D; + + GLFrameBufferObject(int width, int height); + virtual ~GLFrameBufferObject(); + bool isComplete(); + virtual bool failed() const {return m_failed;} +protected: + void setAsRenderTarget(bool state = true); + GLuint m_fbo; + GLuint m_depthBuffer; + int m_width, m_height; + bool m_failed; +}; + +class GLTexture2D : public GLTexture +{ +public: + GLTexture2D(int width, int height); + GLTexture2D(const QString& fileName, int width = 0, int height = 0); + void load(int width, int height, QRgb *data); + virtual void bind(); + virtual void unbind(); +}; + +class GLTexture3D : public GLTexture +{ +public: + GLTexture3D(int width, int height, int depth); + // TODO: Implement function below + //GLTexture3D(const QString& fileName, int width = 0, int height = 0); + void load(int width, int height, int depth, QRgb *data); + virtual void bind(); + virtual void unbind(); +}; + +class GLTextureCube : public GLTexture +{ +public: + GLTextureCube(int size); + GLTextureCube(const QStringList& fileNames, int size = 0); + void load(int size, int face, QRgb *data); + virtual void bind(); + virtual void unbind(); +}; + +// TODO: Define and implement class below +//class GLRenderTarget2D : public GLTexture2D + +class GLRenderTargetCube : public GLTextureCube +{ +public: + GLRenderTargetCube(int size); + // begin rendering to one of the cube's faces. 0 <= face < 6 + void begin(int face); + // end rendering + void end(); + virtual bool failed() const {return m_failed || m_fbo.failed();} + + static void getViewMatrix(QMatrix4x4& mat, int face); + static void getProjectionMatrix(QMatrix4x4& mat, float nearZ, float farZ); +private: + GLFrameBufferObject m_fbo; +}; + +struct VertexDescription +{ + enum + { + Null = 0, // Terminates a VertexDescription array + Position, + TexCoord, + Normal, + Color, + }; + int field; // Position, TexCoord, Normal, Color + int type; // GL_FLOAT, GL_UNSIGNED_BYTE + int count; // number of elements + int offset; // field's offset into vertex struct + int index; // 0 (unused at the moment) +}; + +// Implementation of interleaved buffers. +// 'T' is a struct which must include a null-terminated static array +// 'VertexDescription* description'. +// Example: +/* +struct Vertex +{ + GLfloat position[3]; + GLfloat texCoord[2]; + GLfloat normal[3]; + GLbyte color[4]; + static VertexDescription description[]; +}; + +VertexDescription Vertex::description[] = { + {VertexDescription::Position, GL_FLOAT, SIZE_OF_MEMBER(Vertex, position) / sizeof(GLfloat), offsetof(Vertex, position), 0}, + {VertexDescription::TexCoord, GL_FLOAT, SIZE_OF_MEMBER(Vertex, texCoord) / sizeof(GLfloat), offsetof(Vertex, texCoord), 0}, + {VertexDescription::Normal, GL_FLOAT, SIZE_OF_MEMBER(Vertex, normal) / sizeof(GLfloat), offsetof(Vertex, normal), 0}, + {VertexDescription::Color, GL_BYTE, SIZE_OF_MEMBER(Vertex, color) / sizeof(GLbyte), offsetof(Vertex, color), 0}, + {VertexDescription::Null, 0, 0, 0, 0}, +}; +*/ +template<class T> +class GLVertexBuffer +{ +public: + GLVertexBuffer(int length, const T *data = 0, int mode = GL_STATIC_DRAW) + : m_length(0) + , m_mode(mode) + , m_buffer(0) + , m_failed(false) + { + GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::GLVertexBuffer", glGenBuffers && glBindBuffer && glBufferData, return) + + glGenBuffers(1, &m_buffer); + glBindBuffer(GL_ARRAY_BUFFER, m_buffer); + glBufferData(GL_ARRAY_BUFFER, (m_length = length) * sizeof(T), data, mode); + } + + ~GLVertexBuffer() + { + GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::~GLVertexBuffer", glDeleteBuffers, return) + + glDeleteBuffers(1, &m_buffer); + } + + void bind() + { + GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::bind", glBindBuffer, return) + + glBindBuffer(GL_ARRAY_BUFFER, m_buffer); + for (VertexDescription *desc = T::description; desc->field != VertexDescription::Null; ++desc) { + switch (desc->field) { + case VertexDescription::Position: + glVertexPointer(desc->count, desc->type, sizeof(T), BUFFER_OFFSET(desc->offset)); + glEnableClientState(GL_VERTEX_ARRAY); + break; + case VertexDescription::TexCoord: + glTexCoordPointer(desc->count, desc->type, sizeof(T), BUFFER_OFFSET(desc->offset)); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + break; + case VertexDescription::Normal: + glNormalPointer(desc->type, sizeof(T), BUFFER_OFFSET(desc->offset)); + glEnableClientState(GL_NORMAL_ARRAY); + break; + case VertexDescription::Color: + glColorPointer(desc->count, desc->type, sizeof(T), BUFFER_OFFSET(desc->offset)); + glEnableClientState(GL_COLOR_ARRAY); + break; + default: + break; + } + } + } + + void unbind() + { + GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::unbind", glBindBuffer, return) + + glBindBuffer(GL_ARRAY_BUFFER, 0); + for (VertexDescription *desc = T::description; desc->field != VertexDescription::Null; ++desc) { + switch (desc->field) { + case VertexDescription::Position: + glDisableClientState(GL_VERTEX_ARRAY); + break; + case VertexDescription::TexCoord: + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + break; + case VertexDescription::Normal: + glDisableClientState(GL_NORMAL_ARRAY); + break; + case VertexDescription::Color: + glDisableClientState(GL_COLOR_ARRAY); + break; + default: + break; + } + } + } + + int length() const {return m_length;} + + T *lock() + { + GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::lock", glBindBuffer && glMapBuffer, return 0) + + glBindBuffer(GL_ARRAY_BUFFER, m_buffer); + //glBufferData(GL_ARRAY_BUFFER, m_length, NULL, m_mode); + GLvoid* buffer = glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE); + m_failed = (buffer == 0); + return reinterpret_cast<T *>(buffer); + } + + void unlock() + { + GLBUFFERS_ASSERT_OPENGL("GLVertexBuffer::unlock", glBindBuffer && glUnmapBuffer, return) + + glBindBuffer(GL_ARRAY_BUFFER, m_buffer); + glUnmapBuffer(GL_ARRAY_BUFFER); + } + + bool failed() + { + return m_failed; + } + +private: + int m_length, m_mode; + GLuint m_buffer; + bool m_failed; +}; + +template<class T> +class GLIndexBuffer +{ +public: + GLIndexBuffer(int length, const T *data = 0, int mode = GL_STATIC_DRAW) + : m_length(0) + , m_mode(mode) + , m_buffer(0) + , m_failed(false) + { + GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::GLIndexBuffer", glGenBuffers && glBindBuffer && glBufferData, return) + + glGenBuffers(1, &m_buffer); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, (m_length = length) * sizeof(T), data, mode); + } + + ~GLIndexBuffer() + { + GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::~GLIndexBuffer", glDeleteBuffers, return) + + glDeleteBuffers(1, &m_buffer); + } + + void bind() + { + GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::bind", glBindBuffer, return) + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer); + } + + void unbind() + { + GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::unbind", glBindBuffer, return) + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } + + int length() const {return m_length;} + + T *lock() + { + GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::lock", glBindBuffer && glMapBuffer, return 0) + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer); + GLvoid* buffer = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_WRITE); + m_failed = (buffer == 0); + return reinterpret_cast<T *>(buffer); + } + + void unlock() + { + GLBUFFERS_ASSERT_OPENGL("GLIndexBuffer::unlock", glBindBuffer && glUnmapBuffer, return) + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer); + glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); + } + + bool failed() + { + return m_failed; + } + +private: + int m_length, m_mode; + GLuint m_buffer; + bool m_failed; +}; + +#endif diff --git a/examples/widgets/graphicsview/boxes/glextensions.cpp b/examples/widgets/graphicsview/boxes/glextensions.cpp new file mode 100644 index 0000000000..ada8f457f6 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/glextensions.cpp @@ -0,0 +1,98 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "glextensions.h" + +#define RESOLVE_GL_FUNC(f) ok &= bool((f = (_gl##f) context->getProcAddress(QLatin1String("gl" #f)))); + +bool GLExtensionFunctions::resolve(const QGLContext *context) +{ + bool ok = true; + + RESOLVE_GL_FUNC(GenFramebuffersEXT) + RESOLVE_GL_FUNC(GenRenderbuffersEXT) + RESOLVE_GL_FUNC(BindRenderbufferEXT) + RESOLVE_GL_FUNC(RenderbufferStorageEXT) + RESOLVE_GL_FUNC(DeleteFramebuffersEXT) + RESOLVE_GL_FUNC(DeleteRenderbuffersEXT) + RESOLVE_GL_FUNC(BindFramebufferEXT) + RESOLVE_GL_FUNC(FramebufferTexture2DEXT) + RESOLVE_GL_FUNC(FramebufferRenderbufferEXT) + RESOLVE_GL_FUNC(CheckFramebufferStatusEXT) + + RESOLVE_GL_FUNC(ActiveTexture) + RESOLVE_GL_FUNC(TexImage3D) + + RESOLVE_GL_FUNC(GenBuffers) + RESOLVE_GL_FUNC(BindBuffer) + RESOLVE_GL_FUNC(BufferData) + RESOLVE_GL_FUNC(DeleteBuffers) + RESOLVE_GL_FUNC(MapBuffer) + RESOLVE_GL_FUNC(UnmapBuffer) + + return ok; +} + +bool GLExtensionFunctions::fboSupported() { + return GenFramebuffersEXT + && GenRenderbuffersEXT + && BindRenderbufferEXT + && RenderbufferStorageEXT + && DeleteFramebuffersEXT + && DeleteRenderbuffersEXT + && BindFramebufferEXT + && FramebufferTexture2DEXT + && FramebufferRenderbufferEXT + && CheckFramebufferStatusEXT; +} + +bool GLExtensionFunctions::openGL15Supported() { + return ActiveTexture + && TexImage3D + && GenBuffers + && BindBuffer + && BufferData + && DeleteBuffers + && MapBuffer + && UnmapBuffer; +} + +#undef RESOLVE_GL_FUNC diff --git a/examples/widgets/graphicsview/boxes/glextensions.h b/examples/widgets/graphicsview/boxes/glextensions.h new file mode 100644 index 0000000000..35dd9a047c --- /dev/null +++ b/examples/widgets/graphicsview/boxes/glextensions.h @@ -0,0 +1,202 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef GLEXTENSIONS_H +#define GLEXTENSIONS_H + +#include <QtOpenGL> + +/* +Functions resolved: + +glGenFramebuffersEXT +glGenRenderbuffersEXT +glBindRenderbufferEXT +glRenderbufferStorageEXT +glDeleteFramebuffersEXT +glDeleteRenderbuffersEXT +glBindFramebufferEXT +glFramebufferTexture2DEXT +glFramebufferRenderbufferEXT +glCheckFramebufferStatusEXT + +glActiveTexture +glTexImage3D + +glGenBuffers +glBindBuffer +glBufferData +glDeleteBuffers +glMapBuffer +glUnmapBuffer +*/ + +#ifndef Q_OS_MAC +# ifndef APIENTRYP +# ifdef APIENTRY +# define APIENTRYP APIENTRY * +# else +# define APIENTRY +# define APIENTRYP * +# endif +# endif +#else +# define APIENTRY +# define APIENTRYP * +#endif + +#ifndef GL_VERSION_1_2 +#define GL_TEXTURE_3D 0x806F +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_BGRA 0x80E1 +#endif + +#ifndef GL_VERSION_1_3 +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +//#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +//#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +//#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#endif + +#ifndef GL_ARB_vertex_buffer_object +typedef ptrdiff_t GLsizeiptrARB; +#endif + +#ifndef GL_VERSION_1_5 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_READ_WRITE 0x88BA +#define GL_STATIC_DRAW 0x88E4 +#endif + +#ifndef GL_EXT_framebuffer_object +#define GL_RENDERBUFFER_EXT 0x8D41 +#define GL_FRAMEBUFFER_EXT 0x8D40 +#define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 +#define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 +#define GL_DEPTH_ATTACHMENT_EXT 0x8D00 +#endif + +typedef void (APIENTRY *_glGenFramebuffersEXT) (GLsizei, GLuint *); +typedef void (APIENTRY *_glGenRenderbuffersEXT) (GLsizei, GLuint *); +typedef void (APIENTRY *_glBindRenderbufferEXT) (GLenum, GLuint); +typedef void (APIENTRY *_glRenderbufferStorageEXT) (GLenum, GLenum, GLsizei, GLsizei); +typedef void (APIENTRY *_glDeleteFramebuffersEXT) (GLsizei, const GLuint*); +typedef void (APIENTRY *_glDeleteRenderbuffersEXT) (GLsizei, const GLuint*); +typedef void (APIENTRY *_glBindFramebufferEXT) (GLenum, GLuint); +typedef void (APIENTRY *_glFramebufferTexture2DEXT) (GLenum, GLenum, GLenum, GLuint, GLint); +typedef void (APIENTRY *_glFramebufferRenderbufferEXT) (GLenum, GLenum, GLenum, GLuint); +typedef GLenum (APIENTRY *_glCheckFramebufferStatusEXT) (GLenum); + +typedef void (APIENTRY *_glActiveTexture) (GLenum); +typedef void (APIENTRY *_glTexImage3D) (GLenum, GLint, GLenum, GLsizei, GLsizei, GLsizei, GLint, GLenum, GLenum, const GLvoid *); + +typedef void (APIENTRY *_glGenBuffers) (GLsizei, GLuint *); +typedef void (APIENTRY *_glBindBuffer) (GLenum, GLuint); +typedef void (APIENTRY *_glBufferData) (GLenum, GLsizeiptrARB, const GLvoid *, GLenum); +typedef void (APIENTRY *_glDeleteBuffers) (GLsizei, const GLuint *); +typedef void *(APIENTRY *_glMapBuffer) (GLenum, GLenum); +typedef GLboolean (APIENTRY *_glUnmapBuffer) (GLenum); + +struct GLExtensionFunctions +{ + bool resolve(const QGLContext *context); + + bool fboSupported(); + bool openGL15Supported(); // the rest: multi-texture, 3D-texture, vertex buffer objects + + _glGenFramebuffersEXT GenFramebuffersEXT; + _glGenRenderbuffersEXT GenRenderbuffersEXT; + _glBindRenderbufferEXT BindRenderbufferEXT; + _glRenderbufferStorageEXT RenderbufferStorageEXT; + _glDeleteFramebuffersEXT DeleteFramebuffersEXT; + _glDeleteRenderbuffersEXT DeleteRenderbuffersEXT; + _glBindFramebufferEXT BindFramebufferEXT; + _glFramebufferTexture2DEXT FramebufferTexture2DEXT; + _glFramebufferRenderbufferEXT FramebufferRenderbufferEXT; + _glCheckFramebufferStatusEXT CheckFramebufferStatusEXT; + + _glActiveTexture ActiveTexture; + _glTexImage3D TexImage3D; + + _glGenBuffers GenBuffers; + _glBindBuffer BindBuffer; + _glBufferData BufferData; + _glDeleteBuffers DeleteBuffers; + _glMapBuffer MapBuffer; + _glUnmapBuffer UnmapBuffer; +}; + +inline GLExtensionFunctions &getGLExtensionFunctions() +{ + static GLExtensionFunctions funcs; + return funcs; +} + +#define glGenFramebuffersEXT getGLExtensionFunctions().GenFramebuffersEXT +#define glGenRenderbuffersEXT getGLExtensionFunctions().GenRenderbuffersEXT +#define glBindRenderbufferEXT getGLExtensionFunctions().BindRenderbufferEXT +#define glRenderbufferStorageEXT getGLExtensionFunctions().RenderbufferStorageEXT +#define glDeleteFramebuffersEXT getGLExtensionFunctions().DeleteFramebuffersEXT +#define glDeleteRenderbuffersEXT getGLExtensionFunctions().DeleteRenderbuffersEXT +#define glBindFramebufferEXT getGLExtensionFunctions().BindFramebufferEXT +#define glFramebufferTexture2DEXT getGLExtensionFunctions().FramebufferTexture2DEXT +#define glFramebufferRenderbufferEXT getGLExtensionFunctions().FramebufferRenderbufferEXT +#define glCheckFramebufferStatusEXT getGLExtensionFunctions().CheckFramebufferStatusEXT + +#define glActiveTexture getGLExtensionFunctions().ActiveTexture +#define glTexImage3D getGLExtensionFunctions().TexImage3D + +#define glGenBuffers getGLExtensionFunctions().GenBuffers +#define glBindBuffer getGLExtensionFunctions().BindBuffer +#define glBufferData getGLExtensionFunctions().BufferData +#define glDeleteBuffers getGLExtensionFunctions().DeleteBuffers +#define glMapBuffer getGLExtensionFunctions().MapBuffer +#define glUnmapBuffer getGLExtensionFunctions().UnmapBuffer + +#endif diff --git a/examples/widgets/graphicsview/boxes/gltrianglemesh.h b/examples/widgets/graphicsview/boxes/gltrianglemesh.h new file mode 100644 index 0000000000..2c9ab01c3f --- /dev/null +++ b/examples/widgets/graphicsview/boxes/gltrianglemesh.h @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef GLTRIANGLEMESH_H +#define GLTRIANGLEMESH_H + +//#include <GL/glew.h> +#include "glextensions.h" + +#include <QtWidgets> +#include <QtOpenGL> + +#include "glbuffers.h" + +template<class TVertex, class TIndex> +class GLTriangleMesh +{ +public: + GLTriangleMesh(int vertexCount, int indexCount) : m_vb(vertexCount), m_ib(indexCount) + { + } + + virtual ~GLTriangleMesh() + { + } + + virtual void draw() + { + if (failed()) + return; + + int type = GL_UNSIGNED_INT; + if (sizeof(TIndex) == sizeof(char)) type = GL_UNSIGNED_BYTE; + if (sizeof(TIndex) == sizeof(short)) type = GL_UNSIGNED_SHORT; + + m_vb.bind(); + m_ib.bind(); + glDrawElements(GL_TRIANGLES, m_ib.length(), type, BUFFER_OFFSET(0)); + m_vb.unbind(); + m_ib.unbind(); + } + + bool failed() + { + return m_vb.failed() || m_ib.failed(); + } +protected: + GLVertexBuffer<TVertex> m_vb; + GLIndexBuffer<TIndex> m_ib; +}; + + +#endif diff --git a/examples/widgets/graphicsview/boxes/granite.fsh b/examples/widgets/graphicsview/boxes/granite.fsh new file mode 100644 index 0000000000..175420f351 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/granite.fsh @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform sampler3D noise; + +//const vec4 graniteColors[3] = {vec4(0.0, 0.0, 0.0, 1), vec4(0.30, 0.15, 0.10, 1), vec4(0.80, 0.70, 0.75, 1)}; +uniform vec4 graniteColors[3]; + +float steep(float x) +{ + return clamp(5.0 * x - 2.0, 0.0, 1.0); +} + +void main() +{ + vec2 turbulence = vec2(0, 0); + float scale = 1.0; + for (int i = 0; i < 4; ++i) { + turbulence += scale * (texture3D(noise, gl_TexCoord[1].xyz / scale).xy - 0.5); + scale *= 0.5; + } + + vec3 N = normalize(normal); + // assume directional light + + gl_MaterialParameters M = gl_FrontMaterial; + + float NdotL = dot(N, lightDirection.xyz); + float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); + + vec4 unlitColor = mix(graniteColors[1], mix(graniteColors[0], graniteColors[2], steep(0.5 + turbulence.y)), 4.0 * abs(turbulence.x)); + gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + + M.specular * specular * pow(max(RdotL, 0.0), M.shininess); +} diff --git a/examples/widgets/graphicsview/boxes/main.cpp b/examples/widgets/graphicsview/boxes/main.cpp new file mode 100644 index 0000000000..2baa539d3a --- /dev/null +++ b/examples/widgets/graphicsview/boxes/main.cpp @@ -0,0 +1,150 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//#include <GL/glew.h> +#include "glextensions.h" + +#include "scene.h" + +#include <QtWidgets> +#include <QGLWidget> + +class GraphicsView : public QGraphicsView +{ +public: + GraphicsView() + { + setWindowTitle(tr("Boxes")); + setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + //setRenderHints(QPainter::SmoothPixmapTransform); + } + +protected: + void resizeEvent(QResizeEvent *event) { + if (scene()) + scene()->setSceneRect(QRect(QPoint(0, 0), event->size())); + QGraphicsView::resizeEvent(event); + } +}; + +inline bool matchString(const char *extensionString, const char *subString) +{ + int subStringLength = strlen(subString); + return (strncmp(extensionString, subString, subStringLength) == 0) + && ((extensionString[subStringLength] == ' ') || (extensionString[subStringLength] == '\0')); +} + +bool necessaryExtensionsSupported() +{ + const char *extensionString = reinterpret_cast<const char *>(glGetString(GL_EXTENSIONS)); + const char *p = extensionString; + + const int GL_EXT_FBO = 1; + const int GL_ARB_VS = 2; + const int GL_ARB_FS = 4; + const int GL_ARB_SO = 8; + int extensions = 0; + + while (*p) { + if (matchString(p, "GL_EXT_framebuffer_object")) + extensions |= GL_EXT_FBO; + else if (matchString(p, "GL_ARB_vertex_shader")) + extensions |= GL_ARB_VS; + else if (matchString(p, "GL_ARB_fragment_shader")) + extensions |= GL_ARB_FS; + else if (matchString(p, "GL_ARB_shader_objects")) + extensions |= GL_ARB_SO; + while ((*p != ' ') && (*p != '\0')) + ++p; + if (*p == ' ') + ++p; + } + return (extensions == 15); +} + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_1_5) == 0) { + QMessageBox::critical(0, "OpenGL features missing", + "OpenGL version 1.5 or higher is required to run this demo.\n" + "The program will now exit."); + return -1; + } + + int maxTextureSize = 1024; + QGLWidget *widget = new QGLWidget(QGLFormat(QGL::SampleBuffers)); + widget->makeCurrent(); + + if (!necessaryExtensionsSupported()) { + QMessageBox::critical(0, "OpenGL features missing", + "The OpenGL extensions required to run this demo are missing.\n" + "The program will now exit."); + delete widget; + return -2; + } + + // Check if all the necessary functions are resolved. + if (!getGLExtensionFunctions().resolve(widget->context())) { + QMessageBox::critical(0, "OpenGL features missing", + "Failed to resolve OpenGL functions required to run this demo.\n" + "The program will now exit."); + delete widget; + return -3; + } + + // TODO: Make conditional for final release + QMessageBox::information(0, "For your information", + "This demo can be GPU and CPU intensive and may\n" + "work poorly or not at all on your system."); + + widget->makeCurrent(); // The current context must be set before calling Scene's constructor + Scene scene(1024, 768, maxTextureSize); + GraphicsView view; + view.setViewport(widget); + view.setViewportUpdateMode(QGraphicsView::FullViewportUpdate); + view.setScene(&scene); + view.show(); + + return app.exec(); +} + diff --git a/examples/widgets/graphicsview/boxes/marble.fsh b/examples/widgets/graphicsview/boxes/marble.fsh new file mode 100644 index 0000000000..3985a98e96 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/marble.fsh @@ -0,0 +1,71 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform sampler3D noise; + +//const vec4 marbleColors[2] = {vec4(0.9, 0.9, 0.9, 1), vec4(0.6, 0.5, 0.5, 1)}; +uniform vec4 marbleColors[2]; + +void main() +{ + float turbulence = 0.0; + float scale = 1.0; + for (int i = 0; i < 4; ++i) { + turbulence += scale * (texture3D(noise, 0.125 * gl_TexCoord[1].xyz / scale).x - 0.5); + scale *= 0.5; + } + + vec3 N = normalize(normal); + // assume directional light + + gl_MaterialParameters M = gl_FrontMaterial; + + float NdotL = dot(N, lightDirection.xyz); + float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); + + vec4 unlitColor = mix(marbleColors[0], marbleColors[1], exp(-4.0 * abs(turbulence))); + gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + + M.specular * specular * pow(max(RdotL, 0.0), M.shininess); +} diff --git a/examples/widgets/graphicsview/boxes/parameters.par b/examples/widgets/graphicsview/boxes/parameters.par new file mode 100644 index 0000000000..50e20739b9 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/parameters.par @@ -0,0 +1,5 @@ +color basicColor ff0e3d0e +color woodColors ff5e3d33 ffcc9966 +float woodTubulence 0.1 +color graniteColors ff000000 ff4d261a ffccb3bf +color marbleColors ffe6e6e6 ff998080 diff --git a/examples/widgets/graphicsview/boxes/qt-logo.jpg b/examples/widgets/graphicsview/boxes/qt-logo.jpg Binary files differnew file mode 100644 index 0000000000..4014b4659c --- /dev/null +++ b/examples/widgets/graphicsview/boxes/qt-logo.jpg diff --git a/examples/widgets/graphicsview/boxes/qt-logo.png b/examples/widgets/graphicsview/boxes/qt-logo.png Binary files differnew file mode 100644 index 0000000000..7d3e97eb36 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/qt-logo.png diff --git a/examples/widgets/graphicsview/boxes/qtbox.cpp b/examples/widgets/graphicsview/boxes/qtbox.cpp new file mode 100644 index 0000000000..cff4497253 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/qtbox.cpp @@ -0,0 +1,480 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qtbox.h" + +const qreal ROTATE_SPEED_X = 30.0 / 1000.0; +const qreal ROTATE_SPEED_Y = 20.0 / 1000.0; +const qreal ROTATE_SPEED_Z = 40.0 / 1000.0; +const int MAX_ITEM_SIZE = 512; +const int MIN_ITEM_SIZE = 16; + +//============================================================================// +// ItemBase // +//============================================================================// + +ItemBase::ItemBase(int size, int x, int y) : m_size(size), m_isResizing(false) +{ + setFlag(QGraphicsItem::ItemIsMovable, true); + setFlag(QGraphicsItem::ItemIsSelectable, true); + setFlag(QGraphicsItem::ItemIsFocusable, true); + setAcceptHoverEvents(true); + setPos(x, y); + m_startTime = QTime::currentTime(); +} + +ItemBase::~ItemBase() +{ +} + +QRectF ItemBase::boundingRect() const +{ + return QRectF(-m_size / 2, -m_size / 2, m_size, m_size); +} + +void ItemBase::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) +{ + if (option->state & QStyle::State_Selected) { + painter->setRenderHint(QPainter::Antialiasing, true); + if (option->state & QStyle::State_HasFocus) + painter->setPen(Qt::yellow); + else + painter->setPen(Qt::white); + painter->drawRect(boundingRect()); + + painter->drawLine(m_size / 2 - 9, m_size / 2, m_size / 2, m_size / 2 - 9); + painter->drawLine(m_size / 2 - 6, m_size / 2, m_size / 2, m_size / 2 - 6); + painter->drawLine(m_size / 2 - 3, m_size / 2, m_size / 2, m_size / 2 - 3); + + painter->setRenderHint(QPainter::Antialiasing, false); + } +} + +void ItemBase::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) +{ + if (!isSelected() && scene()) { + scene()->clearSelection(); + setSelected(true); + } + + QMenu menu; + QAction *delAction = menu.addAction("Delete"); + QAction *newAction = menu.addAction("New"); + QAction *growAction = menu.addAction("Grow"); + QAction *shrinkAction = menu.addAction("Shrink"); + + QAction *selectedAction = menu.exec(event->screenPos()); + + if (selectedAction == delAction) + deleteSelectedItems(scene()); + else if (selectedAction == newAction) + duplicateSelectedItems(scene()); + else if (selectedAction == growAction) + growSelectedItems(scene()); + else if (selectedAction == shrinkAction) + shrinkSelectedItems(scene()); +} + +void ItemBase::duplicateSelectedItems(QGraphicsScene *scene) +{ + if (!scene) + return; + + QList<QGraphicsItem *> selected; + selected = scene->selectedItems(); + + foreach (QGraphicsItem *item, selected) { + ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item); + if (itemBase) + scene->addItem(itemBase->createNew(itemBase->m_size, itemBase->pos().x() + itemBase->m_size, itemBase->pos().y())); + } +} + +void ItemBase::deleteSelectedItems(QGraphicsScene *scene) +{ + if (!scene) + return; + + QList<QGraphicsItem *> selected; + selected = scene->selectedItems(); + + foreach (QGraphicsItem *item, selected) { + ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item); + if (itemBase) + delete itemBase; + } +} + +void ItemBase::growSelectedItems(QGraphicsScene *scene) +{ + if (!scene) + return; + + QList<QGraphicsItem *> selected; + selected = scene->selectedItems(); + + foreach (QGraphicsItem *item, selected) { + ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item); + if (itemBase) { + itemBase->prepareGeometryChange(); + itemBase->m_size *= 2; + if (itemBase->m_size > MAX_ITEM_SIZE) + itemBase->m_size = MAX_ITEM_SIZE; + } + } +} + +void ItemBase::shrinkSelectedItems(QGraphicsScene *scene) +{ + if (!scene) + return; + + QList<QGraphicsItem *> selected; + selected = scene->selectedItems(); + + foreach (QGraphicsItem *item, selected) { + ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item); + if (itemBase) { + itemBase->prepareGeometryChange(); + itemBase->m_size /= 2; + if (itemBase->m_size < MIN_ITEM_SIZE) + itemBase->m_size = MIN_ITEM_SIZE; + } + } +} + +void ItemBase::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +{ + if (m_isResizing) { + int dx = int(2.0 * event->pos().x()); + int dy = int(2.0 * event->pos().y()); + prepareGeometryChange(); + m_size = (dx > dy ? dx : dy); + if (m_size < MIN_ITEM_SIZE) + m_size = MIN_ITEM_SIZE; + else if (m_size > MAX_ITEM_SIZE) + m_size = MAX_ITEM_SIZE; + } else { + QGraphicsItem::mouseMoveEvent(event); + } +} + +void ItemBase::hoverMoveEvent(QGraphicsSceneHoverEvent *event) +{ + if (m_isResizing || (isInResizeArea(event->pos()) && isSelected())) + setCursor(Qt::SizeFDiagCursor); + else + setCursor(Qt::ArrowCursor); + QGraphicsItem::hoverMoveEvent(event); +} + +void ItemBase::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + static qreal z = 0.0; + setZValue(z += 1.0); + if (event->button() == Qt::LeftButton && isInResizeArea(event->pos())) { + m_isResizing = true; + } else { + QGraphicsItem::mousePressEvent(event); + } +} + +void ItemBase::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +{ + if (event->button() == Qt::LeftButton && m_isResizing) { + m_isResizing = false; + } else { + QGraphicsItem::mouseReleaseEvent(event); + } +} + +void ItemBase::keyPressEvent(QKeyEvent *event) +{ + switch (event->key()) { + case Qt::Key_Delete: + deleteSelectedItems(scene()); + break; + case Qt::Key_Insert: + duplicateSelectedItems(scene()); + break; + case Qt::Key_Plus: + growSelectedItems(scene()); + break; + case Qt::Key_Minus: + shrinkSelectedItems(scene()); + break; + default: + QGraphicsItem::keyPressEvent(event); + break; + } +} + +void ItemBase::wheelEvent(QGraphicsSceneWheelEvent *event) +{ + prepareGeometryChange(); + m_size = int(m_size * exp(-event->delta() / 600.0)); + if (m_size > MAX_ITEM_SIZE) + m_size = MAX_ITEM_SIZE; + else if (m_size < MIN_ITEM_SIZE) + m_size = MIN_ITEM_SIZE; +} + +int ItemBase::type() const +{ + return Type; +} + + +bool ItemBase::isInResizeArea(const QPointF &pos) +{ + return (-pos.y() < pos.x() - m_size + 9); +} + +//============================================================================// +// QtBox // +//============================================================================// + +QtBox::QtBox(int size, int x, int y) : ItemBase(size, x, y), m_texture(0) +{ + for (int i = 0; i < 8; ++i) { + m_vertices[i].setX(i & 1 ? 0.5f : -0.5f); + m_vertices[i].setY(i & 2 ? 0.5f : -0.5f); + m_vertices[i].setZ(i & 4 ? 0.5f : -0.5f); + } + for (int i = 0; i < 4; ++i) { + m_texCoords[i].setX(i & 1 ? 1.0f : 0.0f); + m_texCoords[i].setY(i & 2 ? 1.0f : 0.0f); + } + m_normals[0] = QVector3D(-1.0f, 0.0f, 0.0f); + m_normals[1] = QVector3D(1.0f, 0.0f, 0.0f); + m_normals[2] = QVector3D(0.0f, -1.0f, 0.0f); + m_normals[3] = QVector3D(0.0f, 1.0f, 0.0f); + m_normals[4] = QVector3D(0.0f, 0.0f, -1.0f); + m_normals[5] = QVector3D(0.0f, 0.0f, 1.0f); +} + +QtBox::~QtBox() +{ + if (m_texture) + delete m_texture; +} + +ItemBase *QtBox::createNew(int size, int x, int y) +{ + return new QtBox(size, x, y); +} + +void QtBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + QRectF rect = boundingRect().translated(pos()); + float width = float(painter->device()->width()); + float height = float(painter->device()->height()); + + float left = 2.0f * float(rect.left()) / width - 1.0f; + float right = 2.0f * float(rect.right()) / width - 1.0f; + float top = 1.0f - 2.0f * float(rect.top()) / height; + float bottom = 1.0f - 2.0f * float(rect.bottom()) / height; + float moveToRectMatrix[] = { + 0.5f * (right - left), 0.0f, 0.0f, 0.0f, + 0.0f, 0.5f * (bottom - top), 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.5f * (right + left), 0.5f * (bottom + top), 0.0f, 1.0f + }; + + painter->beginNativePainting(); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadMatrixf(moveToRectMatrix); + qgluPerspective(60.0, 1.0, 0.01, 10.0); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + + //glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glEnable(GL_LIGHTING); + glEnable(GL_COLOR_MATERIAL); + glEnable(GL_NORMALIZE); + + if(m_texture == 0) + m_texture = new GLTexture2D(":/res/boxes/qt-logo.jpg", 64, 64); + m_texture->bind(); + glEnable(GL_TEXTURE_2D); + + glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); + float lightColour[] = {1.0f, 1.0f, 1.0f, 1.0f}; + float lightDir[] = {0.0f, 0.0f, 1.0f, 0.0f}; + glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColour); + glLightfv(GL_LIGHT0, GL_POSITION, lightDir); + glEnable(GL_LIGHT0); + + glTranslatef(0.0f, 0.0f, -1.5f); + glRotatef(ROTATE_SPEED_X * m_startTime.msecsTo(QTime::currentTime()), 1.0f, 0.0f, 0.0f); + glRotatef(ROTATE_SPEED_Y * m_startTime.msecsTo(QTime::currentTime()), 0.0f, 1.0f, 0.0f); + glRotatef(ROTATE_SPEED_Z * m_startTime.msecsTo(QTime::currentTime()), 0.0f, 0.0f, 1.0f); + int dt = m_startTime.msecsTo(QTime::currentTime()); + if (dt < 500) + glScalef(dt / 500.0f, dt / 500.0f, dt / 500.0f); + + for (int dir = 0; dir < 3; ++dir) { + glColor4f(1.0f, 1.0f, 1.0f, 1.0); + + glBegin(GL_TRIANGLE_STRIP); + glNormal3fv(reinterpret_cast<float *>(&m_normals[2 * dir + 0])); + for (int i = 0; i < 2; ++i) { + for (int j = 0; j < 2; ++j) { + glTexCoord2fv(reinterpret_cast<float *>(&m_texCoords[(j << 1) | i])); + glVertex3fv(reinterpret_cast<float *>(&m_vertices[(i << ((dir + 2) % 3)) | (j << ((dir + 1) % 3))])); + } + } + glEnd(); + + glBegin(GL_TRIANGLE_STRIP); + glNormal3fv(reinterpret_cast<float *>(&m_normals[2 * dir + 1])); + for (int i = 0; i < 2; ++i) { + for (int j = 0; j < 2; ++j) { + glTexCoord2fv(reinterpret_cast<float *>(&m_texCoords[(j << 1) | i])); + glVertex3fv(reinterpret_cast<float *>(&m_vertices[(1 << dir) | (i << ((dir + 1) % 3)) | (j << ((dir + 2) % 3))])); + } + } + glEnd(); + } + m_texture->unbind(); + + //glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_LIGHTING); + glDisable(GL_COLOR_MATERIAL); + glDisable(GL_TEXTURE_2D); + glDisable(GL_LIGHT0); + glDisable(GL_NORMALIZE); + + glPopMatrix(); + + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + + painter->endNativePainting(); + + ItemBase::paint(painter, option, widget); +} + +//============================================================================// +// CircleItem // +//============================================================================// + +CircleItem::CircleItem(int size, int x, int y) : ItemBase(size, x, y) +{ + m_color = QColor::fromHsv(rand() % 360, 255, 255); +} + +void CircleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + int dt = m_startTime.msecsTo(QTime::currentTime()); + + qreal r0 = 0.5 * m_size * (1.0 - exp(-0.001 * ((dt + 3800) % 4000))); + qreal r1 = 0.5 * m_size * (1.0 - exp(-0.001 * ((dt + 0) % 4000))); + qreal r2 = 0.5 * m_size * (1.0 - exp(-0.001 * ((dt + 1800) % 4000))); + qreal r3 = 0.5 * m_size * (1.0 - exp(-0.001 * ((dt + 2000) % 4000))); + + if (r0 > r1) + r0 = 0.0; + if (r2 > r3) + r2 = 0.0; + + QPainterPath path; + path.moveTo(r1, 0.0); + path.arcTo(-r1, -r1, 2 * r1, 2 * r1, 0.0, 360.0); + path.lineTo(r0, 0.0); + path.arcTo(-r0, -r0, 2 * r0, 2 * r0, 0.0, -360.0); + path.closeSubpath(); + path.moveTo(r3, 0.0); + path.arcTo(-r3, -r3, 2 * r3, 2 * r3, 0.0, 360.0); + path.lineTo(r0, 0.0); + path.arcTo(-r2, -r2, 2 * r2, 2 * r2, 0.0, -360.0); + path.closeSubpath(); + painter->setRenderHint(QPainter::Antialiasing, true); + painter->setBrush(QBrush(m_color)); + painter->setPen(Qt::NoPen); + painter->drawPath(path); + painter->setBrush(Qt::NoBrush); + painter->setPen(Qt::SolidLine); + painter->setRenderHint(QPainter::Antialiasing, false); + + ItemBase::paint(painter, option, widget); +} + +ItemBase *CircleItem::createNew(int size, int x, int y) +{ + return new CircleItem(size, x, y); +} + +//============================================================================// +// SquareItem // +//============================================================================// + +SquareItem::SquareItem(int size, int x, int y) : ItemBase(size, x, y) +{ + m_image = QPixmap(":/res/boxes/square.jpg"); +} + +void SquareItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + int dt = m_startTime.msecsTo(QTime::currentTime()); + QTransform oldTransform = painter->worldTransform(); + int dtMod = dt % 2000; + qreal amp = 0.002 * (dtMod < 1000 ? dtMod : 2000 - dtMod) - 1.0; + + qreal scale = 0.6 + 0.2 * amp * amp; + painter->setWorldTransform(QTransform().rotate(15.0 * amp).scale(scale, scale), true); + + painter->drawPixmap(-m_size / 2, -m_size / 2, m_size, m_size, m_image); + + painter->setWorldTransform(oldTransform, false); + ItemBase::paint(painter, option, widget); +} + +ItemBase *SquareItem::createNew(int size, int x, int y) +{ + return new SquareItem(size, x, y); +} diff --git a/examples/widgets/graphicsview/boxes/qtbox.h b/examples/widgets/graphicsview/boxes/qtbox.h new file mode 100644 index 0000000000..66b9b17b7f --- /dev/null +++ b/examples/widgets/graphicsview/boxes/qtbox.h @@ -0,0 +1,118 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QTBOX_H +#define QTBOX_H + +#include <QtWidgets> + +#include <QtGui/qvector3d.h> +#include "glbuffers.h" + +class ItemBase : public QGraphicsItem +{ +public: + enum { Type = UserType + 1 }; + + ItemBase(int size, int x, int y); + virtual ~ItemBase(); + virtual QRectF boundingRect() const; + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); +protected: + virtual ItemBase *createNew(int size, int x, int y) = 0; + virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); + virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + virtual void hoverMoveEvent(QGraphicsSceneHoverEvent *event); + virtual void mousePressEvent(QGraphicsSceneMouseEvent *event); + virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + virtual void keyPressEvent(QKeyEvent *event); + virtual void wheelEvent(QGraphicsSceneWheelEvent *event); + virtual int type() const; + bool isInResizeArea(const QPointF &pos); + + static void duplicateSelectedItems(QGraphicsScene *scene); + static void deleteSelectedItems(QGraphicsScene *scene); + static void growSelectedItems(QGraphicsScene *scene); + static void shrinkSelectedItems(QGraphicsScene *scene); + + int m_size; + QTime m_startTime; + bool m_isResizing; +}; + +class QtBox : public ItemBase +{ +public: + QtBox(int size, int x, int y); + virtual ~QtBox(); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); +protected: + virtual ItemBase *createNew(int size, int x, int y); +private: + QVector3D m_vertices[8]; + QVector3D m_texCoords[4]; + QVector3D m_normals[6]; + GLTexture *m_texture; +}; + +class CircleItem : public ItemBase +{ +public: + CircleItem(int size, int x, int y); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); +protected: + virtual ItemBase *createNew(int size, int x, int y); + + QColor m_color; +}; + +class SquareItem : public ItemBase +{ +public: + SquareItem(int size, int x, int y); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); +protected: + virtual ItemBase *createNew(int size, int x, int y); + + QPixmap m_image; +}; + +#endif diff --git a/examples/widgets/graphicsview/boxes/reflection.fsh b/examples/widgets/graphicsview/boxes/reflection.fsh new file mode 100644 index 0000000000..95a21112ea --- /dev/null +++ b/examples/widgets/graphicsview/boxes/reflection.fsh @@ -0,0 +1,54 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform samplerCube env; +uniform mat4 view; + +void main() +{ + vec3 N = normalize(normal); + vec3 R = 2.0 * dot(-position, N) * N + position; + gl_FragColor = textureCube(env, R * mat3(view[0].xyz, view[1].xyz, view[2].xyz)); +} diff --git a/examples/widgets/graphicsview/boxes/refraction.fsh b/examples/widgets/graphicsview/boxes/refraction.fsh new file mode 100644 index 0000000000..5411478ea2 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/refraction.fsh @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform samplerCube env; +uniform mat4 view; + +// Arrays don't work here on glsl < 120, apparently. +//const float coeffs[6] = float[6](1.0/2.0, 1.0/2.1, 1.0/2.2, 1.0/2.3, 1.0/2.4, 1.0/2.5); +float coeffs(int i) +{ + return 1.0 / (2.0 + 0.1 * float(i)); +} + +void main() +{ + vec3 N = normalize(normal); + vec3 I = -normalize(position); + float IdotN = dot(I, N); + float scales[6]; + vec3 C[6]; + for (int i = 0; i < 6; ++i) { + scales[i] = (IdotN - sqrt(1.0 - coeffs(i) + coeffs(i) * (IdotN * IdotN))); + C[i] = textureCube(env, (-I + coeffs(i) * N) * mat3(view[0].xyz, view[1].xyz, view[2].xyz)).xyz; + } + + gl_FragColor = 0.25 * vec4(C[5].x + 2.0*C[0].x + C[1].x, C[1].y + 2.0*C[2].y + C[3].y, + C[3].z + 2.0*C[4].z + C[5].z, 4.0); +} diff --git a/examples/widgets/graphicsview/boxes/roundedbox.cpp b/examples/widgets/graphicsview/boxes/roundedbox.cpp new file mode 100644 index 0000000000..e205dbdb2b --- /dev/null +++ b/examples/widgets/graphicsview/boxes/roundedbox.cpp @@ -0,0 +1,161 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "roundedbox.h" + +//============================================================================// +// P3T2N3Vertex // +//============================================================================// + +VertexDescription P3T2N3Vertex::description[] = { + {VertexDescription::Position, GL_FLOAT, SIZE_OF_MEMBER(P3T2N3Vertex, position) / sizeof(float), 0, 0}, + {VertexDescription::TexCoord, GL_FLOAT, SIZE_OF_MEMBER(P3T2N3Vertex, texCoord) / sizeof(float), sizeof(QVector3D), 0}, + {VertexDescription::Normal, GL_FLOAT, SIZE_OF_MEMBER(P3T2N3Vertex, normal) / sizeof(float), sizeof(QVector3D) + sizeof(QVector2D), 0}, + + {VertexDescription::Null, 0, 0, 0, 0}, +}; + +//============================================================================// +// GLRoundedBox // +//============================================================================// + +float lerp(float a, float b, float t) +{ + return a * (1.0f - t) + b * t; +} + +GLRoundedBox::GLRoundedBox(float r, float scale, int n) + : GLTriangleMesh<P3T2N3Vertex, unsigned short>((n+2)*(n+3)*4, (n+1)*(n+1)*24+36+72*(n+1)) +{ + int vidx = 0, iidx = 0; + int vertexCountPerCorner = (n + 2) * (n + 3) / 2; + + P3T2N3Vertex *vp = m_vb.lock(); + unsigned short *ip = m_ib.lock(); + + if (!vp || !ip) { + qWarning("GLRoundedBox::GLRoundedBox: Failed to lock vertex buffer and/or index buffer."); + m_ib.unlock(); + m_vb.unlock(); + return; + } + + for (int corner = 0; corner < 8; ++corner) { + QVector3D centre(corner & 1 ? 1.0f : -1.0f, + corner & 2 ? 1.0f : -1.0f, + corner & 4 ? 1.0f : -1.0f); + int winding = (corner & 1) ^ ((corner >> 1) & 1) ^ (corner >> 2); + int offsX = ((corner ^ 1) - corner) * vertexCountPerCorner; + int offsY = ((corner ^ 2) - corner) * vertexCountPerCorner; + int offsZ = ((corner ^ 4) - corner) * vertexCountPerCorner; + + // Face polygons + if (winding) { + ip[iidx++] = vidx; + ip[iidx++] = vidx + offsX; + ip[iidx++] = vidx + offsY; + + ip[iidx++] = vidx + vertexCountPerCorner - n - 2; + ip[iidx++] = vidx + vertexCountPerCorner - n - 2 + offsY; + ip[iidx++] = vidx + vertexCountPerCorner - n - 2 + offsZ; + + ip[iidx++] = vidx + vertexCountPerCorner - 1; + ip[iidx++] = vidx + vertexCountPerCorner - 1 + offsZ; + ip[iidx++] = vidx + vertexCountPerCorner - 1 + offsX; + } + + for (int i = 0; i < n + 2; ++i) { + + // Edge polygons + if (winding && i < n + 1) { + ip[iidx++] = vidx + i + 1; + ip[iidx++] = vidx; + ip[iidx++] = vidx + offsY + i + 1; + ip[iidx++] = vidx + offsY; + ip[iidx++] = vidx + offsY + i + 1; + ip[iidx++] = vidx; + + ip[iidx++] = vidx + i; + ip[iidx++] = vidx + 2 * i + 2; + ip[iidx++] = vidx + i + offsX; + ip[iidx++] = vidx + 2 * i + offsX + 2; + ip[iidx++] = vidx + i + offsX; + ip[iidx++] = vidx + 2 * i + 2; + + ip[iidx++] = (corner + 1) * vertexCountPerCorner - 1 - i; + ip[iidx++] = (corner + 1) * vertexCountPerCorner - 2 - i; + ip[iidx++] = (corner + 1) * vertexCountPerCorner - 1 - i + offsZ; + ip[iidx++] = (corner + 1) * vertexCountPerCorner - 2 - i + offsZ; + ip[iidx++] = (corner + 1) * vertexCountPerCorner - 1 - i + offsZ; + ip[iidx++] = (corner + 1) * vertexCountPerCorner - 2 - i; + } + + for (int j = 0; j <= i; ++j) { + QVector3D normal = QVector3D(i - j, j, n + 1 - i).normalized(); + QVector3D offset(0.5f - r, 0.5f - r, 0.5f - r); + QVector3D pos = centre * (offset + r * normal); + + vp[vidx].position = scale * pos; + vp[vidx].normal = centre * normal; + vp[vidx].texCoord = QVector2D(pos.x() + 0.5f, pos.y() + 0.5f); + + // Corner polygons + if (i < n + 1) { + ip[iidx++] = vidx; + ip[iidx++] = vidx + i + 2 - winding; + ip[iidx++] = vidx + i + 1 + winding; + } + if (i < n) { + ip[iidx++] = vidx + i + 1 + winding; + ip[iidx++] = vidx + i + 2 - winding; + ip[iidx++] = vidx + 2 * i + 4; + } + + ++vidx; + } + } + + } + + m_ib.unlock(); + m_vb.unlock(); +} + diff --git a/examples/widgets/graphicsview/boxes/roundedbox.h b/examples/widgets/graphicsview/boxes/roundedbox.h new file mode 100644 index 0000000000..3edfb69fa8 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/roundedbox.h @@ -0,0 +1,72 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ROUNDEDBOX_H +#define ROUNDEDBOX_H + +//#include <GL/glew.h> +#include "glextensions.h" + +#include <QtWidgets> +#include <QtOpenGL> + +#include "gltrianglemesh.h" +#include <QtGui/qvector3d.h> +#include <QtGui/qvector2d.h> +#include "glbuffers.h" + +struct P3T2N3Vertex +{ + QVector3D position; + QVector2D texCoord; + QVector3D normal; + static VertexDescription description[]; +}; + +class GLRoundedBox : public GLTriangleMesh<P3T2N3Vertex, unsigned short> +{ +public: + // 0 < r < 0.5, 0 <= n <= 125 + GLRoundedBox(float r = 0.25f, float scale = 1.0f, int n = 10); +}; + + +#endif diff --git a/examples/widgets/graphicsview/boxes/scene.cpp b/examples/widgets/graphicsview/boxes/scene.cpp new file mode 100644 index 0000000000..5fb43d8c99 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/scene.cpp @@ -0,0 +1,1085 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QDebug> +#include "scene.h" +#include <QtGui/qmatrix4x4.h> +#include <QtGui/qvector3d.h> + +#include "3rdparty/fbm.h" + +void checkGLErrors(const QString& prefix) +{ + switch (glGetError()) { + case GL_NO_ERROR: + //qDebug() << prefix << tr("No error."); + break; + case GL_INVALID_ENUM: + qDebug() << prefix << QObject::tr("Invalid enum."); + break; + case GL_INVALID_VALUE: + qDebug() << prefix << QObject::tr("Invalid value."); + break; + case GL_INVALID_OPERATION: + qDebug() << prefix << QObject::tr("Invalid operation."); + break; + case GL_STACK_OVERFLOW: + qDebug() << prefix << QObject::tr("Stack overflow."); + break; + case GL_STACK_UNDERFLOW: + qDebug() << prefix << QObject::tr("Stack underflow."); + break; + case GL_OUT_OF_MEMORY: + qDebug() << prefix << QObject::tr("Out of memory."); + break; + default: + qDebug() << prefix << QObject::tr("Unknown error."); + break; + } +} + +//============================================================================// +// ColorEdit // +//============================================================================// + +ColorEdit::ColorEdit(QRgb initialColor, int id) + : m_color(initialColor), m_id(id) +{ + QHBoxLayout *layout = new QHBoxLayout; + setLayout(layout); + layout->setContentsMargins(0, 0, 0, 0); + + m_lineEdit = new QLineEdit(QString::number(m_color, 16)); + layout->addWidget(m_lineEdit); + + m_button = new QFrame; + QPalette palette = m_button->palette(); + palette.setColor(QPalette::Window, QColor(m_color)); + m_button->setPalette(palette); + m_button->setAutoFillBackground(true); + m_button->setMinimumSize(32, 0); + m_button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred); + m_button->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); + layout->addWidget(m_button); + + connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(editDone())); +} + +void ColorEdit::editDone() +{ + bool ok; + QRgb newColor = m_lineEdit->text().toUInt(&ok, 16); + if (ok) + setColor(newColor); +} + +void ColorEdit::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) { + QColor color(m_color); + QColorDialog dialog(color, 0); + dialog.setOption(QColorDialog::ShowAlphaChannel, true); +// The ifdef block is a workaround for the beta, TODO: remove when bug 238525 is fixed +#ifdef Q_WS_MAC + dialog.setOption(QColorDialog::DontUseNativeDialog, true); +#endif + dialog.move(280, 120); + if (dialog.exec() == QDialog::Rejected) + return; + QRgb newColor = dialog.selectedColor().rgba(); + if (newColor == m_color) + return; + setColor(newColor); + } +} + +void ColorEdit::setColor(QRgb color) +{ + m_color = color; + m_lineEdit->setText(QString::number(m_color, 16)); // "Clean up" text + QPalette palette = m_button->palette(); + palette.setColor(QPalette::Window, QColor(m_color)); + m_button->setPalette(palette); + emit colorChanged(m_color, m_id); +} + +//============================================================================// +// FloatEdit // +//============================================================================// + +FloatEdit::FloatEdit(float initialValue, int id) + : m_value(initialValue), m_id(id) +{ + QHBoxLayout *layout = new QHBoxLayout; + setLayout(layout); + layout->setContentsMargins(0, 0, 0, 0); + + m_lineEdit = new QLineEdit(QString::number(m_value)); + layout->addWidget(m_lineEdit); + + connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(editDone())); +} + +void FloatEdit::editDone() +{ + bool ok; + float newValue = m_lineEdit->text().toFloat(&ok); + if (ok) { + m_value = newValue; + m_lineEdit->setText(QString::number(m_value)); // "Clean up" text + emit valueChanged(m_value, m_id); + } +} + +//============================================================================// +// TwoSidedGraphicsWidget // +//============================================================================// + +TwoSidedGraphicsWidget::TwoSidedGraphicsWidget(QGraphicsScene *scene) + : QObject(scene) + , m_current(0) + , m_angle(0) + , m_delta(0) +{ + for (int i = 0; i < 2; ++i) + m_proxyWidgets[i] = 0; +} + +void TwoSidedGraphicsWidget::setWidget(int index, QWidget *widget) +{ + if (index < 0 || index >= 2) + { + qWarning("TwoSidedGraphicsWidget::setWidget: Index out of bounds, index == %d", index); + return; + } + + GraphicsWidget *proxy = new GraphicsWidget; + proxy->setWidget(widget); + + if (m_proxyWidgets[index]) + delete m_proxyWidgets[index]; + m_proxyWidgets[index] = proxy; + + proxy->setCacheMode(QGraphicsItem::ItemCoordinateCache); + proxy->setZValue(1e30); // Make sure the dialog is drawn on top of all other (OpenGL) items + + if (index != m_current) + proxy->setVisible(false); + + qobject_cast<QGraphicsScene *>(parent())->addItem(proxy); +} + +QWidget *TwoSidedGraphicsWidget::widget(int index) +{ + if (index < 0 || index >= 2) + { + qWarning("TwoSidedGraphicsWidget::widget: Index out of bounds, index == %d", index); + return 0; + } + return m_proxyWidgets[index]->widget(); +} + +void TwoSidedGraphicsWidget::flip() +{ + m_delta = (m_current == 0 ? 9 : -9); + animateFlip(); +} + +void TwoSidedGraphicsWidget::animateFlip() +{ + m_angle += m_delta; + if (m_angle == 90) { + int old = m_current; + m_current ^= 1; + m_proxyWidgets[old]->setVisible(false); + m_proxyWidgets[m_current]->setVisible(true); + m_proxyWidgets[m_current]->setGeometry(m_proxyWidgets[old]->geometry()); + } + + QRectF r = m_proxyWidgets[m_current]->boundingRect(); + m_proxyWidgets[m_current]->setTransform(QTransform() + .translate(r.width() / 2, r.height() / 2) + .rotate(m_angle - 180 * m_current, Qt::YAxis) + .translate(-r.width() / 2, -r.height() / 2)); + + if ((m_current == 0 && m_angle > 0) || (m_current == 1 && m_angle < 180)) + QTimer::singleShot(25, this, SLOT(animateFlip())); +} + +QVariant GraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &value) +{ + if (change == ItemPositionChange && scene()) { + QRectF rect = boundingRect(); + QPointF pos = value.toPointF(); + QRectF sceneRect = scene()->sceneRect(); + if (pos.x() + rect.left() < sceneRect.left()) + pos.setX(sceneRect.left() - rect.left()); + else if (pos.x() + rect.right() >= sceneRect.right()) + pos.setX(sceneRect.right() - rect.right()); + if (pos.y() + rect.top() < sceneRect.top()) + pos.setY(sceneRect.top() - rect.top()); + else if (pos.y() + rect.bottom() >= sceneRect.bottom()) + pos.setY(sceneRect.bottom() - rect.bottom()); + return pos; + } + return QGraphicsProxyWidget::itemChange(change, value); +} + +void GraphicsWidget::resizeEvent(QGraphicsSceneResizeEvent *event) +{ + setCacheMode(QGraphicsItem::NoCache); + setCacheMode(QGraphicsItem::ItemCoordinateCache); + QGraphicsProxyWidget::resizeEvent(event); +} + +void GraphicsWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + painter->setRenderHint(QPainter::Antialiasing, false); + QGraphicsProxyWidget::paint(painter, option, widget); + //painter->setRenderHint(QPainter::Antialiasing, true); +} + +//============================================================================// +// RenderOptionsDialog // +//============================================================================// + +RenderOptionsDialog::RenderOptionsDialog() + : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint) +{ + setWindowOpacity(0.75); + setWindowTitle(tr("Options (double click to flip)")); + QGridLayout *layout = new QGridLayout; + setLayout(layout); + layout->setColumnStretch(1, 1); + + int row = 0; + + QCheckBox *check = new QCheckBox(tr("Dynamic cube map")); + check->setCheckState(Qt::Unchecked); + // Dynamic cube maps are only enabled when multi-texturing and render to texture are available. + check->setEnabled(glActiveTexture && glGenFramebuffersEXT); + connect(check, SIGNAL(stateChanged(int)), this, SIGNAL(dynamicCubemapToggled(int))); + layout->addWidget(check, 0, 0, 1, 2); + ++row; + + QPalette palette; + + // Load all .par files + // .par files have a simple syntax for specifying user adjustable uniform variables. + QSet<QByteArray> uniforms; + QList<QString> filter = QStringList("*.par"); + QList<QFileInfo> files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); + + foreach (QFileInfo fileInfo, files) { + QFile file(fileInfo.absoluteFilePath()); + if (file.open(QIODevice::ReadOnly)) { + while (!file.atEnd()) { + QList<QByteArray> tokens = file.readLine().simplified().split(' '); + QList<QByteArray>::const_iterator it = tokens.begin(); + if (it == tokens.end()) + continue; + QByteArray type = *it; + if (++it == tokens.end()) + continue; + QByteArray name = *it; + bool singleElement = (tokens.size() == 3); // type, name and one value + char counter[10] = "000000000"; + int counterPos = 8; // position of last digit + while (++it != tokens.end()) { + m_parameterNames << name; + if (!singleElement) { + m_parameterNames.back() += "["; + m_parameterNames.back() += counter + counterPos; + m_parameterNames.back() += "]"; + int j = 8; // position of last digit + ++counter[j]; + while (j > 0 && counter[j] > '9') { + counter[j] = '0'; + ++counter[--j]; + } + if (j < counterPos) + counterPos = j; + } + + if (type == "color") { + layout->addWidget(new QLabel(m_parameterNames.back())); + bool ok; + ColorEdit *colorEdit = new ColorEdit(it->toUInt(&ok, 16), m_parameterNames.size() - 1); + m_parameterEdits << colorEdit; + layout->addWidget(colorEdit); + connect(colorEdit, SIGNAL(colorChanged(QRgb,int)), this, SLOT(setColorParameter(QRgb,int))); + ++row; + } else if (type == "float") { + layout->addWidget(new QLabel(m_parameterNames.back())); + bool ok; + FloatEdit *floatEdit = new FloatEdit(it->toFloat(&ok), m_parameterNames.size() - 1); + m_parameterEdits << floatEdit; + layout->addWidget(floatEdit); + connect(floatEdit, SIGNAL(valueChanged(float,int)), this, SLOT(setFloatParameter(float,int))); + ++row; + } + } + } + file.close(); + } + } + + layout->addWidget(new QLabel(tr("Texture:"))); + m_textureCombo = new QComboBox; + connect(m_textureCombo, SIGNAL(currentIndexChanged(int)), this, SIGNAL(textureChanged(int))); + layout->addWidget(m_textureCombo); + ++row; + + layout->addWidget(new QLabel(tr("Shader:"))); + m_shaderCombo = new QComboBox; + connect(m_shaderCombo, SIGNAL(currentIndexChanged(int)), this, SIGNAL(shaderChanged(int))); + layout->addWidget(m_shaderCombo); + ++row; + + layout->setRowStretch(row, 1); +} + +int RenderOptionsDialog::addTexture(const QString &name) +{ + m_textureCombo->addItem(name); + return m_textureCombo->count() - 1; +} + +int RenderOptionsDialog::addShader(const QString &name) +{ + m_shaderCombo->addItem(name); + return m_shaderCombo->count() - 1; +} + +void RenderOptionsDialog::emitParameterChanged() +{ + foreach (ParameterEdit *edit, m_parameterEdits) + edit->emitChange(); +} + +void RenderOptionsDialog::setColorParameter(QRgb color, int id) +{ + emit colorParameterChanged(m_parameterNames[id], color); +} + +void RenderOptionsDialog::setFloatParameter(float value, int id) +{ + emit floatParameterChanged(m_parameterNames[id], value); +} + +void RenderOptionsDialog::mouseDoubleClickEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) + emit doubleClicked(); +} + +//============================================================================// +// ItemDialog // +//============================================================================// + +ItemDialog::ItemDialog() + : QDialog(0, Qt::CustomizeWindowHint | Qt::WindowTitleHint) +{ + setWindowTitle(tr("Items (double click to flip)")); + setWindowOpacity(0.75); + resize(160, 100); + + QVBoxLayout *layout = new QVBoxLayout; + setLayout(layout); + QPushButton *button; + + button = new QPushButton(tr("Add Qt box")); + layout->addWidget(button); + connect(button, SIGNAL(clicked()), this, SLOT(triggerNewQtBox())); + + button = new QPushButton(tr("Add circle")); + layout->addWidget(button); + connect(button, SIGNAL(clicked()), this, SLOT(triggerNewCircleItem())); + + button = new QPushButton(tr("Add square")); + layout->addWidget(button); + connect(button, SIGNAL(clicked()), this, SLOT(triggerNewSquareItem())); + + layout->addStretch(1); +} + +void ItemDialog::triggerNewQtBox() +{ + emit newItemTriggered(QtBoxItem); +} + +void ItemDialog::triggerNewCircleItem() +{ + emit newItemTriggered(CircleItem); +} + +void ItemDialog::triggerNewSquareItem() +{ + emit newItemTriggered(SquareItem); +} + +void ItemDialog::mouseDoubleClickEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) + emit doubleClicked(); +} + +//============================================================================// +// Scene // +//============================================================================// + +const static char environmentShaderText[] = + "uniform samplerCube env;" + "void main() {" + "gl_FragColor = textureCube(env, gl_TexCoord[1].xyz);" + "}"; + +Scene::Scene(int width, int height, int maxTextureSize) + : m_distExp(600) + , m_frame(0) + , m_maxTextureSize(maxTextureSize) + , m_currentShader(0) + , m_currentTexture(0) + , m_dynamicCubemap(false) + , m_updateAllCubemaps(true) + , m_box(0) + , m_vertexShader(0) + , m_environmentShader(0) + , m_environmentProgram(0) +{ + setSceneRect(0, 0, width, height); + + m_trackBalls[0] = TrackBall(0.05f, QVector3D(0, 1, 0), TrackBall::Sphere); + m_trackBalls[1] = TrackBall(0.005f, QVector3D(0, 0, 1), TrackBall::Sphere); + m_trackBalls[2] = TrackBall(0.0f, QVector3D(0, 1, 0), TrackBall::Plane); + + m_renderOptions = new RenderOptionsDialog; + m_renderOptions->move(20, 120); + m_renderOptions->resize(m_renderOptions->sizeHint()); + + connect(m_renderOptions, SIGNAL(dynamicCubemapToggled(int)), this, SLOT(toggleDynamicCubemap(int))); + connect(m_renderOptions, SIGNAL(colorParameterChanged(QString,QRgb)), this, SLOT(setColorParameter(QString,QRgb))); + connect(m_renderOptions, SIGNAL(floatParameterChanged(QString,float)), this, SLOT(setFloatParameter(QString,float))); + connect(m_renderOptions, SIGNAL(textureChanged(int)), this, SLOT(setTexture(int))); + connect(m_renderOptions, SIGNAL(shaderChanged(int)), this, SLOT(setShader(int))); + + m_itemDialog = new ItemDialog; + connect(m_itemDialog, SIGNAL(newItemTriggered(ItemDialog::ItemType)), this, SLOT(newItem(ItemDialog::ItemType))); + + TwoSidedGraphicsWidget *twoSided = new TwoSidedGraphicsWidget(this); + twoSided->setWidget(0, m_renderOptions); + twoSided->setWidget(1, m_itemDialog); + + connect(m_renderOptions, SIGNAL(doubleClicked()), twoSided, SLOT(flip())); + connect(m_itemDialog, SIGNAL(doubleClicked()), twoSided, SLOT(flip())); + + addItem(new QtBox(64, width - 64, height - 64)); + addItem(new QtBox(64, width - 64, 64)); + addItem(new QtBox(64, 64, height - 64)); + addItem(new QtBox(64, 64, 64)); + + initGL(); + + m_timer = new QTimer(this); + m_timer->setInterval(20); + connect(m_timer, SIGNAL(timeout()), this, SLOT(update())); + m_timer->start(); + + m_time.start(); +} + +Scene::~Scene() +{ + if (m_box) + delete m_box; + foreach (GLTexture *texture, m_textures) + if (texture) delete texture; + if (m_mainCubemap) + delete m_mainCubemap; + foreach (QGLShaderProgram *program, m_programs) + if (program) delete program; + if (m_vertexShader) + delete m_vertexShader; + foreach (QGLShader *shader, m_fragmentShaders) + if (shader) delete shader; + foreach (GLRenderTargetCube *rt, m_cubemaps) + if (rt) delete rt; + if (m_environmentShader) + delete m_environmentShader; + if (m_environmentProgram) + delete m_environmentProgram; +} + +void Scene::initGL() +{ + m_box = new GLRoundedBox(0.25f, 1.0f, 10); + + m_vertexShader = new QGLShader(QGLShader::Vertex); + m_vertexShader->compileSourceFile(QLatin1String(":/res/boxes/basic.vsh")); + + QStringList list; + list << ":/res/boxes/cubemap_posx.jpg" << ":/res/boxes/cubemap_negx.jpg" << ":/res/boxes/cubemap_posy.jpg" + << ":/res/boxes/cubemap_negy.jpg" << ":/res/boxes/cubemap_posz.jpg" << ":/res/boxes/cubemap_negz.jpg"; + m_environment = new GLTextureCube(list, qMin(1024, m_maxTextureSize)); + m_environmentShader = new QGLShader(QGLShader::Fragment); + m_environmentShader->compileSourceCode(environmentShaderText); + m_environmentProgram = new QGLShaderProgram; + m_environmentProgram->addShader(m_vertexShader); + m_environmentProgram->addShader(m_environmentShader); + m_environmentProgram->link(); + + const int NOISE_SIZE = 128; // for a different size, B and BM in fbm.c must also be changed + m_noise = new GLTexture3D(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE); + QRgb *data = new QRgb[NOISE_SIZE * NOISE_SIZE * NOISE_SIZE]; + memset(data, 0, NOISE_SIZE * NOISE_SIZE * NOISE_SIZE * sizeof(QRgb)); + QRgb *p = data; + float pos[3]; + for (int k = 0; k < NOISE_SIZE; ++k) { + pos[2] = k * (0x20 / (float)NOISE_SIZE); + for (int j = 0; j < NOISE_SIZE; ++j) { + for (int i = 0; i < NOISE_SIZE; ++i) { + for (int byte = 0; byte < 4; ++byte) { + pos[0] = (i + (byte & 1) * 16) * (0x20 / (float)NOISE_SIZE); + pos[1] = (j + (byte & 2) * 8) * (0x20 / (float)NOISE_SIZE); + *p |= (int)(128.0f * (noise3(pos) + 1.0f)) << (byte * 8); + } + ++p; + } + } + } + m_noise->load(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE, data); + delete[] data; + + m_mainCubemap = new GLRenderTargetCube(512); + + QStringList filter; + QList<QFileInfo> files; + + // Load all .png files as textures + m_currentTexture = 0; + filter = QStringList("*.png"); + files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); + + foreach (QFileInfo file, files) { + GLTexture *texture = new GLTexture2D(file.absoluteFilePath(), qMin(256, m_maxTextureSize), qMin(256, m_maxTextureSize)); + if (texture->failed()) { + delete texture; + continue; + } + m_textures << texture; + m_renderOptions->addTexture(file.baseName()); + } + + if (m_textures.size() == 0) + m_textures << new GLTexture2D(qMin(64, m_maxTextureSize), qMin(64, m_maxTextureSize)); + + // Load all .fsh files as fragment shaders + m_currentShader = 0; + filter = QStringList("*.fsh"); + files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); + foreach (QFileInfo file, files) { + QGLShaderProgram *program = new QGLShaderProgram; + QGLShader* shader = new QGLShader(QGLShader::Fragment); + shader->compileSourceFile(file.absoluteFilePath()); + // The program does not take ownership over the shaders, so store them in a vector so they can be deleted afterwards. + program->addShader(m_vertexShader); + program->addShader(shader); + if (!program->link()) { + qWarning("Failed to compile and link shader program"); + qWarning("Vertex shader log:"); + qWarning() << m_vertexShader->log(); + qWarning() << "Fragment shader log ( file =" << file.absoluteFilePath() << "):"; + qWarning() << shader->log(); + qWarning("Shader program log:"); + qWarning() << program->log(); + + delete shader; + delete program; + continue; + } + + m_fragmentShaders << shader; + m_programs << program; + m_renderOptions->addShader(file.baseName()); + + program->bind(); + m_cubemaps << ((program->uniformLocation("env") != -1) ? new GLRenderTargetCube(qMin(256, m_maxTextureSize)) : 0); + program->release(); + } + + if (m_programs.size() == 0) + m_programs << new QGLShaderProgram; + + m_renderOptions->emitParameterChanged(); +} + +static void loadMatrix(const QMatrix4x4& m) +{ + // static to prevent glLoadMatrixf to fail on certain drivers + static GLfloat mat[16]; + const qreal *data = m.constData(); + for (int index = 0; index < 16; ++index) + mat[index] = data[index]; + glLoadMatrixf(mat); +} + +static void multMatrix(const QMatrix4x4& m) +{ + // static to prevent glMultMatrixf to fail on certain drivers + static GLfloat mat[16]; + const qreal *data = m.constData(); + for (int index = 0; index < 16; ++index) + mat[index] = data[index]; + glMultMatrixf(mat); +} + +// If one of the boxes should not be rendered, set excludeBox to its index. +// If the main box should not be rendered, set excludeBox to -1. +void Scene::renderBoxes(const QMatrix4x4 &view, int excludeBox) +{ + QMatrix4x4 invView = view.inverted(); + + // If multi-texturing is supported, use three saplers. + if (glActiveTexture) { + glActiveTexture(GL_TEXTURE0); + m_textures[m_currentTexture]->bind(); + glActiveTexture(GL_TEXTURE2); + m_noise->bind(); + glActiveTexture(GL_TEXTURE1); + } else { + m_textures[m_currentTexture]->bind(); + } + + glDisable(GL_LIGHTING); + glDisable(GL_CULL_FACE); + + QMatrix4x4 viewRotation(view); + viewRotation(3, 0) = viewRotation(3, 1) = viewRotation(3, 2) = 0.0f; + viewRotation(0, 3) = viewRotation(1, 3) = viewRotation(2, 3) = 0.0f; + viewRotation(3, 3) = 1.0f; + loadMatrix(viewRotation); + glScalef(20.0f, 20.0f, 20.0f); + + // Don't render the environment if the environment texture can't be set for the correct sampler. + if (glActiveTexture) { + m_environment->bind(); + m_environmentProgram->bind(); + m_environmentProgram->setUniformValue("tex", GLint(0)); + m_environmentProgram->setUniformValue("env", GLint(1)); + m_environmentProgram->setUniformValue("noise", GLint(2)); + m_box->draw(); + m_environmentProgram->release(); + m_environment->unbind(); + } + + loadMatrix(view); + + glEnable(GL_CULL_FACE); + glEnable(GL_LIGHTING); + + for (int i = 0; i < m_programs.size(); ++i) { + if (i == excludeBox) + continue; + + glPushMatrix(); + QMatrix4x4 m; + m.rotate(m_trackBalls[1].rotation()); + multMatrix(m); + + glRotatef(360.0f * i / m_programs.size(), 0.0f, 0.0f, 1.0f); + glTranslatef(2.0f, 0.0f, 0.0f); + glScalef(0.3f, 0.6f, 0.6f); + + if (glActiveTexture) { + if (m_dynamicCubemap && m_cubemaps[i]) + m_cubemaps[i]->bind(); + else + m_environment->bind(); + } + m_programs[i]->bind(); + m_programs[i]->setUniformValue("tex", GLint(0)); + m_programs[i]->setUniformValue("env", GLint(1)); + m_programs[i]->setUniformValue("noise", GLint(2)); + m_programs[i]->setUniformValue("view", view); + m_programs[i]->setUniformValue("invView", invView); + m_box->draw(); + m_programs[i]->release(); + + if (glActiveTexture) { + if (m_dynamicCubemap && m_cubemaps[i]) + m_cubemaps[i]->unbind(); + else + m_environment->unbind(); + } + glPopMatrix(); + } + + if (-1 != excludeBox) { + QMatrix4x4 m; + m.rotate(m_trackBalls[0].rotation()); + multMatrix(m); + + if (glActiveTexture) { + if (m_dynamicCubemap) + m_mainCubemap->bind(); + else + m_environment->bind(); + } + + m_programs[m_currentShader]->bind(); + m_programs[m_currentShader]->setUniformValue("tex", GLint(0)); + m_programs[m_currentShader]->setUniformValue("env", GLint(1)); + m_programs[m_currentShader]->setUniformValue("noise", GLint(2)); + m_programs[m_currentShader]->setUniformValue("view", view); + m_programs[m_currentShader]->setUniformValue("invView", invView); + m_box->draw(); + m_programs[m_currentShader]->release(); + + if (glActiveTexture) { + if (m_dynamicCubemap) + m_mainCubemap->unbind(); + else + m_environment->unbind(); + } + } + + if (glActiveTexture) { + glActiveTexture(GL_TEXTURE2); + m_noise->unbind(); + glActiveTexture(GL_TEXTURE0); + } + m_textures[m_currentTexture]->unbind(); +} + +void Scene::setStates() +{ + //glClearColor(0.25f, 0.25f, 0.5f, 1.0f); + + glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glEnable(GL_LIGHTING); + //glEnable(GL_COLOR_MATERIAL); + glEnable(GL_TEXTURE_2D); + glEnable(GL_NORMALIZE); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadIdentity(); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + + setLights(); + + float materialSpecular[] = {0.5f, 0.5f, 0.5f, 1.0f}; + glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, materialSpecular); + glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 32.0f); +} + +void Scene::setLights() +{ + glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); + //float lightColour[] = {1.0f, 1.0f, 1.0f, 1.0f}; + float lightDir[] = {0.0f, 0.0f, 1.0f, 0.0f}; + //glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColour); + //glLightfv(GL_LIGHT0, GL_SPECULAR, lightColour); + glLightfv(GL_LIGHT0, GL_POSITION, lightDir); + glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 1.0f); + glEnable(GL_LIGHT0); +} + +void Scene::defaultStates() +{ + //glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + + glDisable(GL_DEPTH_TEST); + glDisable(GL_CULL_FACE); + glDisable(GL_LIGHTING); + //glDisable(GL_COLOR_MATERIAL); + glDisable(GL_TEXTURE_2D); + glDisable(GL_LIGHT0); + glDisable(GL_NORMALIZE); + + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); + + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + + glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, 0.0f); + float defaultMaterialSpecular[] = {0.0f, 0.0f, 0.0f, 1.0f}; + glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, defaultMaterialSpecular); + glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 0.0f); +} + +void Scene::renderCubemaps() +{ + // To speed things up, only update the cubemaps for the small cubes every N frames. + const int N = (m_updateAllCubemaps ? 1 : 3); + + QMatrix4x4 mat; + GLRenderTargetCube::getProjectionMatrix(mat, 0.1f, 100.0f); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + loadMatrix(mat); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + + QVector3D center; + + for (int i = m_frame % N; i < m_cubemaps.size(); i += N) { + if (0 == m_cubemaps[i]) + continue; + + float angle = 2.0f * PI * i / m_cubemaps.size(); + + center = m_trackBalls[1].rotation().rotatedVector(QVector3D(cos(angle), sin(angle), 0.0f)); + + for (int face = 0; face < 6; ++face) { + m_cubemaps[i]->begin(face); + + GLRenderTargetCube::getViewMatrix(mat, face); + QVector4D v = QVector4D(-center.x(), -center.y(), -center.z(), 1.0); + mat.setColumn(3, mat * v); + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + renderBoxes(mat, i); + + m_cubemaps[i]->end(); + } + } + + for (int face = 0; face < 6; ++face) { + m_mainCubemap->begin(face); + GLRenderTargetCube::getViewMatrix(mat, face); + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + renderBoxes(mat, -1); + + m_mainCubemap->end(); + } + + glPopMatrix(); + + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + + m_updateAllCubemaps = false; +} + +void Scene::drawBackground(QPainter *painter, const QRectF &) +{ + float width = float(painter->device()->width()); + float height = float(painter->device()->height()); + + painter->beginNativePainting(); + setStates(); + + if (m_dynamicCubemap) + renderCubemaps(); + + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + glMatrixMode(GL_PROJECTION); + qgluPerspective(60.0, width / height, 0.01, 15.0); + + glMatrixMode(GL_MODELVIEW); + + QMatrix4x4 view; + view.rotate(m_trackBalls[2].rotation()); + view(2, 3) -= 2.0f * exp(m_distExp / 1200.0f); + renderBoxes(view); + + defaultStates(); + ++m_frame; + + painter->endNativePainting(); +} + +QPointF Scene::pixelPosToViewPos(const QPointF& p) +{ + return QPointF(2.0 * float(p.x()) / width() - 1.0, + 1.0 - 2.0 * float(p.y()) / height()); +} + +void Scene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +{ + QGraphicsScene::mouseMoveEvent(event); + if (event->isAccepted()) + return; + + if (event->buttons() & Qt::LeftButton) { + m_trackBalls[0].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + event->accept(); + } else { + m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + } + + if (event->buttons() & Qt::RightButton) { + m_trackBalls[1].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + event->accept(); + } else { + m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + } + + if (event->buttons() & Qt::MidButton) { + m_trackBalls[2].move(pixelPosToViewPos(event->scenePos()), QQuaternion()); + event->accept(); + } else { + m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion()); + } +} + +void Scene::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + QGraphicsScene::mousePressEvent(event); + if (event->isAccepted()) + return; + + if (event->buttons() & Qt::LeftButton) { + m_trackBalls[0].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + event->accept(); + } + + if (event->buttons() & Qt::RightButton) { + m_trackBalls[1].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + event->accept(); + } + + if (event->buttons() & Qt::MidButton) { + m_trackBalls[2].push(pixelPosToViewPos(event->scenePos()), QQuaternion()); + event->accept(); + } +} + +void Scene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +{ + QGraphicsScene::mouseReleaseEvent(event); + if (event->isAccepted()) + return; + + if (event->button() == Qt::LeftButton) { + m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + event->accept(); + } + + if (event->button() == Qt::RightButton) { + m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugate()); + event->accept(); + } + + if (event->button() == Qt::MidButton) { + m_trackBalls[2].release(pixelPosToViewPos(event->scenePos()), QQuaternion()); + event->accept(); + } +} + +void Scene::wheelEvent(QGraphicsSceneWheelEvent * event) +{ + QGraphicsScene::wheelEvent(event); + if (!event->isAccepted()) { + m_distExp += event->delta(); + if (m_distExp < -8 * 120) + m_distExp = -8 * 120; + if (m_distExp > 10 * 120) + m_distExp = 10 * 120; + event->accept(); + } +} + +void Scene::setShader(int index) +{ + if (index >= 0 && index < m_fragmentShaders.size()) + m_currentShader = index; +} + +void Scene::setTexture(int index) +{ + if (index >= 0 && index < m_textures.size()) + m_currentTexture = index; +} + +void Scene::toggleDynamicCubemap(int state) +{ + if ((m_dynamicCubemap = (state == Qt::Checked))) + m_updateAllCubemaps = true; +} + +void Scene::setColorParameter(const QString &name, QRgb color) +{ + // set the color in all programs + foreach (QGLShaderProgram *program, m_programs) { + program->bind(); + program->setUniformValue(program->uniformLocation(name), QColor(color)); + program->release(); + } +} + +void Scene::setFloatParameter(const QString &name, float value) +{ + // set the color in all programs + foreach (QGLShaderProgram *program, m_programs) { + program->bind(); + program->setUniformValue(program->uniformLocation(name), value); + program->release(); + } +} + +void Scene::newItem(ItemDialog::ItemType type) +{ + QSize size = sceneRect().size().toSize(); + switch (type) { + case ItemDialog::QtBoxItem: + addItem(new QtBox(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32)); + break; + case ItemDialog::CircleItem: + addItem(new CircleItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32)); + break; + case ItemDialog::SquareItem: + addItem(new SquareItem(64, rand() % (size.width() - 64) + 32, rand() % (size.height() - 64) + 32)); + break; + default: + break; + } +} diff --git a/examples/widgets/graphicsview/boxes/scene.h b/examples/widgets/graphicsview/boxes/scene.h new file mode 100644 index 0000000000..9410f7f994 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/scene.h @@ -0,0 +1,245 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SCENE_H +#define SCENE_H + +//#include <GL/glew.h> +#include "glextensions.h" + +#include <QtWidgets> +#include <QtOpenGL> + +#include "roundedbox.h" +#include "gltrianglemesh.h" +#include "trackball.h" +#include "glbuffers.h" +#include "qtbox.h" + +#define PI 3.14159265358979 + +QT_BEGIN_NAMESPACE +class QMatrix4x4; +QT_END_NAMESPACE + +class ParameterEdit : public QWidget +{ +public: + virtual void emitChange() = 0; +}; + +class ColorEdit : public ParameterEdit +{ + Q_OBJECT +public: + ColorEdit(QRgb initialColor, int id); + QRgb color() const {return m_color;} + virtual void emitChange() {emit colorChanged(m_color, m_id);} +public slots: + void editDone(); +signals: + void colorChanged(QRgb color, int id); +protected: + virtual void mousePressEvent(QMouseEvent *event); + void setColor(QRgb color); // also emits colorChanged() +private: + QGraphicsScene *m_dialogParentScene; + QLineEdit *m_lineEdit; + QFrame *m_button; + QRgb m_color; + int m_id; +}; + +class FloatEdit : public ParameterEdit +{ + Q_OBJECT +public: + FloatEdit(float initialValue, int id); + float value() const {return m_value;} + virtual void emitChange() {emit valueChanged(m_value, m_id);} +public slots: + void editDone(); +signals: + void valueChanged(float value, int id); +private: + QGraphicsScene *m_dialogParentScene; + QLineEdit *m_lineEdit; + float m_value; + int m_id; +}; + +class GraphicsWidget : public QGraphicsProxyWidget +{ +public: + GraphicsWidget() : QGraphicsProxyWidget(0, Qt::Window) {} +protected: + virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value); + virtual void resizeEvent(QGraphicsSceneResizeEvent *event); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); +}; + +class TwoSidedGraphicsWidget : public QObject +{ + Q_OBJECT +public: + TwoSidedGraphicsWidget(QGraphicsScene *scene); + void setWidget(int index, QWidget *widget); + QWidget *widget(int index); +public slots: + void flip(); +protected slots: + void animateFlip(); +private: + GraphicsWidget *m_proxyWidgets[2]; + int m_current; + int m_angle; // angle in degrees + int m_delta; +}; + +class RenderOptionsDialog : public QDialog +{ + Q_OBJECT +public: + RenderOptionsDialog(); + int addTexture(const QString &name); + int addShader(const QString &name); + void emitParameterChanged(); +protected slots: + void setColorParameter(QRgb color, int id); + void setFloatParameter(float value, int id); +signals: + void dynamicCubemapToggled(int); + void colorParameterChanged(const QString &, QRgb); + void floatParameterChanged(const QString &, float); + void textureChanged(int); + void shaderChanged(int); + void doubleClicked(); +protected: + virtual void mouseDoubleClickEvent(QMouseEvent *event); + + QVector<QByteArray> m_parameterNames; + QComboBox *m_textureCombo; + QComboBox *m_shaderCombo; + QVector<ParameterEdit *> m_parameterEdits; +}; + +class ItemDialog : public QDialog +{ + Q_OBJECT +public: + enum ItemType { + QtBoxItem, + CircleItem, + SquareItem, + }; + + ItemDialog(); +public slots: + void triggerNewQtBox(); + void triggerNewCircleItem(); + void triggerNewSquareItem(); +signals: + void doubleClicked(); + void newItemTriggered(ItemDialog::ItemType type); +protected: + virtual void mouseDoubleClickEvent(QMouseEvent *event); +}; + +class Scene : public QGraphicsScene +{ + Q_OBJECT +public: + Scene(int width, int height, int maxTextureSize); + ~Scene(); + virtual void drawBackground(QPainter *painter, const QRectF &rect); + +public slots: + void setShader(int index); + void setTexture(int index); + void toggleDynamicCubemap(int state); + void setColorParameter(const QString &name, QRgb color); + void setFloatParameter(const QString &name, float value); + void newItem(ItemDialog::ItemType type); +protected: + void renderBoxes(const QMatrix4x4 &view, int excludeBox = -2); + void setStates(); + void setLights(); + void defaultStates(); + void renderCubemaps(); + + virtual void mousePressEvent(QGraphicsSceneMouseEvent *event); + virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + virtual void wheelEvent(QGraphicsSceneWheelEvent * event); +private: + void initGL(); + QPointF pixelPosToViewPos(const QPointF& p); + + QTime m_time; + int m_lastTime; + int m_mouseEventTime; + int m_distExp; + int m_frame; + int m_maxTextureSize; + + int m_currentShader; + int m_currentTexture; + bool m_dynamicCubemap; + bool m_updateAllCubemaps; + + RenderOptionsDialog *m_renderOptions; + ItemDialog *m_itemDialog; + QTimer *m_timer; + GLRoundedBox *m_box; + TrackBall m_trackBalls[3]; + QVector<GLTexture *> m_textures; + GLTextureCube *m_environment; + GLTexture3D *m_noise; + GLRenderTargetCube *m_mainCubemap; + QVector<GLRenderTargetCube *> m_cubemaps; + QVector<QGLShaderProgram *> m_programs; + QGLShader *m_vertexShader; + QVector<QGLShader *> m_fragmentShaders; + QGLShader *m_environmentShader; + QGLShaderProgram *m_environmentProgram; +}; + +#endif diff --git a/examples/widgets/graphicsview/boxes/smiley.png b/examples/widgets/graphicsview/boxes/smiley.png Binary files differnew file mode 100644 index 0000000000..41cfda6b23 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/smiley.png diff --git a/examples/widgets/graphicsview/boxes/square.jpg b/examples/widgets/graphicsview/boxes/square.jpg Binary files differnew file mode 100644 index 0000000000..03f53bd530 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/square.jpg diff --git a/examples/widgets/graphicsview/boxes/trackball.cpp b/examples/widgets/graphicsview/boxes/trackball.cpp new file mode 100644 index 0000000000..b0e9c44628 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/trackball.cpp @@ -0,0 +1,160 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "trackball.h" +#include "scene.h" + +//============================================================================// +// TrackBall // +//============================================================================// + +TrackBall::TrackBall(TrackMode mode) + : m_angularVelocity(0) + , m_paused(false) + , m_pressed(false) + , m_mode(mode) +{ + m_axis = QVector3D(0, 1, 0); + m_rotation = QQuaternion(); + m_lastTime = QTime::currentTime(); +} + +TrackBall::TrackBall(float angularVelocity, const QVector3D& axis, TrackMode mode) + : m_axis(axis) + , m_angularVelocity(angularVelocity) + , m_paused(false) + , m_pressed(false) + , m_mode(mode) +{ + m_rotation = QQuaternion(); + m_lastTime = QTime::currentTime(); +} + +void TrackBall::push(const QPointF& p, const QQuaternion &) +{ + m_rotation = rotation(); + m_pressed = true; + m_lastTime = QTime::currentTime(); + m_lastPos = p; + m_angularVelocity = 0.0f; +} + +void TrackBall::move(const QPointF& p, const QQuaternion &transformation) +{ + if (!m_pressed) + return; + + QTime currentTime = QTime::currentTime(); + int msecs = m_lastTime.msecsTo(currentTime); + if (msecs <= 20) + return; + + switch (m_mode) { + case Plane: + { + QLineF delta(m_lastPos, p); + m_angularVelocity = 180*delta.length() / (PI*msecs); + m_axis = QVector3D(-delta.dy(), delta.dx(), 0.0f).normalized(); + m_axis = transformation.rotatedVector(m_axis); + m_rotation = QQuaternion::fromAxisAndAngle(m_axis, 180 / PI * delta.length()) * m_rotation; + } + break; + case Sphere: + { + QVector3D lastPos3D = QVector3D(m_lastPos.x(), m_lastPos.y(), 0.0f); + float sqrZ = 1 - QVector3D::dotProduct(lastPos3D, lastPos3D); + if (sqrZ > 0) + lastPos3D.setZ(sqrt(sqrZ)); + else + lastPos3D.normalize(); + + QVector3D currentPos3D = QVector3D(p.x(), p.y(), 0.0f); + sqrZ = 1 - QVector3D::dotProduct(currentPos3D, currentPos3D); + if (sqrZ > 0) + currentPos3D.setZ(sqrt(sqrZ)); + else + currentPos3D.normalize(); + + m_axis = QVector3D::crossProduct(lastPos3D, currentPos3D); + float angle = 180 / PI * asin(sqrt(QVector3D::dotProduct(m_axis, m_axis))); + + m_angularVelocity = angle / msecs; + m_axis.normalize(); + m_axis = transformation.rotatedVector(m_axis); + m_rotation = QQuaternion::fromAxisAndAngle(m_axis, angle) * m_rotation; + } + break; + } + + + m_lastPos = p; + m_lastTime = currentTime; +} + +void TrackBall::release(const QPointF& p, const QQuaternion &transformation) +{ + // Calling move() caused the rotation to stop if the framerate was too low. + move(p, transformation); + m_pressed = false; +} + +void TrackBall::start() +{ + m_lastTime = QTime::currentTime(); + m_paused = false; +} + +void TrackBall::stop() +{ + m_rotation = rotation(); + m_paused = true; +} + +QQuaternion TrackBall::rotation() const +{ + if (m_paused || m_pressed) + return m_rotation; + + QTime currentTime = QTime::currentTime(); + float angle = m_angularVelocity * m_lastTime.msecsTo(currentTime); + return QQuaternion::fromAxisAndAngle(m_axis, angle) * m_rotation; +} + diff --git a/examples/widgets/graphicsview/boxes/trackball.h b/examples/widgets/graphicsview/boxes/trackball.h new file mode 100644 index 0000000000..42a233c4f8 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/trackball.h @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TRACKBALL_H +#define TRACKBALL_H + +#include <QtWidgets> + +#include <QtGui/qvector3d.h> +#include <QtGui/qquaternion.h> + +class TrackBall +{ +public: + enum TrackMode + { + Plane, + Sphere, + }; + TrackBall(TrackMode mode = Sphere); + TrackBall(float angularVelocity, const QVector3D& axis, TrackMode mode = Sphere); + // coordinates in [-1,1]x[-1,1] + void push(const QPointF& p, const QQuaternion &transformation); + void move(const QPointF& p, const QQuaternion &transformation); + void release(const QPointF& p, const QQuaternion &transformation); + void start(); // starts clock + void stop(); // stops clock + QQuaternion rotation() const; +private: + QQuaternion m_rotation; + QVector3D m_axis; + float m_angularVelocity; + + QPointF m_lastPos; + QTime m_lastTime; + bool m_paused; + bool m_pressed; + TrackMode m_mode; +}; + +#endif diff --git a/examples/widgets/graphicsview/boxes/wood.fsh b/examples/widgets/graphicsview/boxes/wood.fsh new file mode 100644 index 0000000000..a722bac869 --- /dev/null +++ b/examples/widgets/graphicsview/boxes/wood.fsh @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +varying vec3 position, normal; +varying vec4 specular, ambient, diffuse, lightDirection; + +uniform sampler2D tex; +uniform sampler3D noise; + +//const vec4 woodColors[2] = {vec4(0.37,0.24,0.20,1), vec4(0.8,0.6,0.4,1)}; +uniform vec4 woodColors[2]; +//const float woodTubulence = 0.1; +uniform float woodTubulence; + +void main() +{ + float r = length(gl_TexCoord[1].yz); + r += woodTubulence * texture3D(noise, 0.25 * gl_TexCoord[1].xyz).x; + + vec3 N = normalize(normal); + // assume directional light + + gl_MaterialParameters M = gl_FrontMaterial; + + float NdotL = dot(N, lightDirection.xyz); + float RdotL = dot(reflect(normalize(position), N), lightDirection.xyz); + + float f = fract(16.0 * r); + vec4 unlitColor = mix(woodColors[0], woodColors[1], min(1.25 * f, 5.0 - 5.0 * f)); + gl_FragColor = (ambient + diffuse * max(NdotL, 0.0)) * unlitColor + + M.specular * specular * pow(max(RdotL, 0.0), M.shininess); +} diff --git a/examples/widgets/graphicsview/chip/chip.cpp b/examples/widgets/graphicsview/chip/chip.cpp new file mode 100644 index 0000000000..665daea1dc --- /dev/null +++ b/examples/widgets/graphicsview/chip/chip.cpp @@ -0,0 +1,183 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "chip.h" + +#include <QtWidgets> + +Chip::Chip(const QColor &color, int x, int y) +{ + this->x = x; + this->y = y; + this->color = color; + setZValue((x + y) % 2); + + setFlags(ItemIsSelectable | ItemIsMovable); + setAcceptHoverEvents(true); +} + +QRectF Chip::boundingRect() const +{ + return QRectF(0, 0, 110, 70); +} + +QPainterPath Chip::shape() const +{ + QPainterPath path; + path.addRect(14, 14, 82, 42); + return path; +} + +void Chip::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + Q_UNUSED(widget); + + QColor fillColor = (option->state & QStyle::State_Selected) ? color.dark(150) : color; + if (option->state & QStyle::State_MouseOver) + fillColor = fillColor.light(125); + + const qreal lod = option->levelOfDetailFromTransform(painter->worldTransform()); + if (lod < 0.2) { + if (lod < 0.125) { + painter->fillRect(QRectF(0, 0, 110, 70), fillColor); + return; + } + + QBrush b = painter->brush(); + painter->setBrush(fillColor); + painter->drawRect(13, 13, 97, 57); + painter->setBrush(b); + return; + } + + QPen oldPen = painter->pen(); + QPen pen = oldPen; + int width = 0; + if (option->state & QStyle::State_Selected) + width += 2; + + pen.setWidth(width); + QBrush b = painter->brush(); + painter->setBrush(QBrush(fillColor.dark(option->state & QStyle::State_Sunken ? 120 : 100))); + + painter->drawRect(QRect(14, 14, 79, 39)); + painter->setBrush(b); + + if (lod >= 1) { + painter->setPen(QPen(Qt::gray, 1)); + painter->drawLine(15, 54, 94, 54); + painter->drawLine(94, 53, 94, 15); + painter->setPen(QPen(Qt::black, 0)); + } + + // Draw text + if (lod >= 2) { + QFont font("Times", 10); + font.setStyleStrategy(QFont::ForceOutline); + painter->setFont(font); + painter->save(); + painter->scale(0.1, 0.1); + painter->drawText(170, 180, QString("Model: VSC-2000 (Very Small Chip) at %1x%2").arg(x).arg(y)); + painter->drawText(170, 200, QString("Serial number: DLWR-WEER-123L-ZZ33-SDSJ")); + painter->drawText(170, 220, QString("Manufacturer: Chip Manufacturer")); + painter->restore(); + } + + // Draw lines + QVarLengthArray<QLineF, 36> lines; + if (lod >= 0.5) { + for (int i = 0; i <= 10; i += (lod > 0.5 ? 1 : 2)) { + lines.append(QLineF(18 + 7 * i, 13, 18 + 7 * i, 5)); + lines.append(QLineF(18 + 7 * i, 54, 18 + 7 * i, 62)); + } + for (int i = 0; i <= 6; i += (lod > 0.5 ? 1 : 2)) { + lines.append(QLineF(5, 18 + i * 5, 13, 18 + i * 5)); + lines.append(QLineF(94, 18 + i * 5, 102, 18 + i * 5)); + } + } + if (lod >= 0.4) { + const QLineF lineData[] = { + QLineF(25, 35, 35, 35), + QLineF(35, 30, 35, 40), + QLineF(35, 30, 45, 35), + QLineF(35, 40, 45, 35), + QLineF(45, 30, 45, 40), + QLineF(45, 35, 55, 35) + }; + lines.append(lineData, 6); + } + painter->drawLines(lines.data(), lines.size()); + + // Draw red ink + if (stuff.size() > 1) { + QPen p = painter->pen(); + painter->setPen(QPen(Qt::red, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + painter->setBrush(Qt::NoBrush); + QPainterPath path; + path.moveTo(stuff.first()); + for (int i = 1; i < stuff.size(); ++i) + path.lineTo(stuff.at(i)); + painter->drawPath(path); + painter->setPen(p); + } +} + +void Chip::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + QGraphicsItem::mousePressEvent(event); + update(); +} + +void Chip::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +{ + if (event->modifiers() & Qt::ShiftModifier) { + stuff << event->pos(); + update(); + return; + } + QGraphicsItem::mouseMoveEvent(event); +} + +void Chip::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +{ + QGraphicsItem::mouseReleaseEvent(event); + update(); +} diff --git a/examples/widgets/graphicsview/chip/chip.h b/examples/widgets/graphicsview/chip/chip.h new file mode 100644 index 0000000000..4c1cfae37d --- /dev/null +++ b/examples/widgets/graphicsview/chip/chip.h @@ -0,0 +1,68 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef CHIP_H +#define CHIP_H + +#include <QtGui/QColor> +#include <QtWidgets/QGraphicsItem> + +class Chip : public QGraphicsItem +{ +public: + Chip(const QColor &color, int x, int y); + + QRectF boundingRect() const; + QPainterPath shape() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget); + +protected: + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + +private: + int x, y; + QColor color; + QVector<QPointF> stuff; +}; + +#endif diff --git a/examples/widgets/graphicsview/chip/chip.pro b/examples/widgets/graphicsview/chip/chip.pro new file mode 100644 index 0000000000..afe748946e --- /dev/null +++ b/examples/widgets/graphicsview/chip/chip.pro @@ -0,0 +1,21 @@ +RESOURCES += images.qrc + +HEADERS += mainwindow.h view.h chip.h +SOURCES += main.cpp +SOURCES += mainwindow.cpp view.cpp chip.cpp + +QT += widgets +!isEmpty(QT.printsupport.name): QT += printsupport +contains(QT_CONFIG, opengl):QT += opengl + +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/chip +sources.files = $$SOURCES $$HEADERS $$RESOURCES *.png *.pro *.html *.doc images +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/chip +INSTALLS += target sources + diff --git a/examples/widgets/graphicsview/chip/fileprint.png b/examples/widgets/graphicsview/chip/fileprint.png Binary files differnew file mode 100644 index 0000000000..ba7c02dc18 --- /dev/null +++ b/examples/widgets/graphicsview/chip/fileprint.png diff --git a/examples/widgets/graphicsview/chip/images.qrc b/examples/widgets/graphicsview/chip/images.qrc new file mode 100644 index 0000000000..c7cdf0c4c0 --- /dev/null +++ b/examples/widgets/graphicsview/chip/images.qrc @@ -0,0 +1,10 @@ +<!DOCTYPE RCC><RCC version="1.0"> +<qresource> + <file>qt4logo.png</file> + <file>zoomin.png</file> + <file>zoomout.png</file> + <file>rotateleft.png</file> + <file>rotateright.png</file> + <file>fileprint.png</file> +</qresource> +</RCC> diff --git a/examples/widgets/graphicsview/chip/main.cpp b/examples/widgets/graphicsview/chip/main.cpp new file mode 100644 index 0000000000..689c806be8 --- /dev/null +++ b/examples/widgets/graphicsview/chip/main.cpp @@ -0,0 +1,57 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "mainwindow.h" + +#include <QApplication> + +int main(int argc, char **argv) +{ + Q_INIT_RESOURCE(images); + + QApplication app(argc, argv); + app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); + + MainWindow window; + window.show(); + + return app.exec(); +} diff --git a/examples/widgets/graphicsview/chip/mainwindow.cpp b/examples/widgets/graphicsview/chip/mainwindow.cpp new file mode 100644 index 0000000000..3d0d295225 --- /dev/null +++ b/examples/widgets/graphicsview/chip/mainwindow.cpp @@ -0,0 +1,109 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "mainwindow.h" +#include "view.h" +#include "chip.h" + +#include <QtWidgets> + +MainWindow::MainWindow(QWidget *parent) + : QWidget(parent) +{ + populateScene(); + + h1Splitter = new QSplitter; + h2Splitter = new QSplitter; + + QSplitter *vSplitter = new QSplitter; + vSplitter->setOrientation(Qt::Vertical); + vSplitter->addWidget(h1Splitter); + vSplitter->addWidget(h2Splitter); + + View *view = new View("Top left view"); + view->view()->setScene(scene); + h1Splitter->addWidget(view); + + view = new View("Top right view"); + view->view()->setScene(scene); + h1Splitter->addWidget(view); + + view = new View("Bottom left view"); + view->view()->setScene(scene); + h2Splitter->addWidget(view); + + view = new View("Bottom right view"); + view->view()->setScene(scene); + h2Splitter->addWidget(view); + + QHBoxLayout *layout = new QHBoxLayout; + layout->addWidget(vSplitter); + setLayout(layout); + + setWindowTitle(tr("Chip Example")); +} + +void MainWindow::populateScene() +{ + scene = new QGraphicsScene; + + QImage image(":/qt4logo.png"); + + // Populate scene + int xx = 0; + int nitems = 0; + for (int i = -11000; i < 11000; i += 110) { + ++xx; + int yy = 0; + for (int j = -7000; j < 7000; j += 70) { + ++yy; + qreal x = (i + 11000) / 22000.0; + qreal y = (j + 7000) / 14000.0; + + QColor color(image.pixel(int(image.width() * x), int(image.height() * y))); + QGraphicsItem *item = new Chip(color, xx, yy); + item->setPos(QPointF(i, j)); + scene->addItem(item); + + ++nitems; + } + } +} diff --git a/examples/widgets/graphicsview/chip/mainwindow.h b/examples/widgets/graphicsview/chip/mainwindow.h new file mode 100644 index 0000000000..18e27a0019 --- /dev/null +++ b/examples/widgets/graphicsview/chip/mainwindow.h @@ -0,0 +1,68 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include <QtWidgets/qwidget.h> + +QT_FORWARD_DECLARE_CLASS(QGraphicsScene) +QT_FORWARD_DECLARE_CLASS(QGraphicsView) +QT_FORWARD_DECLARE_CLASS(QLabel) +QT_FORWARD_DECLARE_CLASS(QSlider) +QT_FORWARD_DECLARE_CLASS(QSplitter) + +class MainWindow : public QWidget +{ + Q_OBJECT +public: + MainWindow(QWidget *parent = 0); + +private: + void setupMatrix(); + void populateScene(); + + QGraphicsScene *scene; + QSplitter *h1Splitter; + QSplitter *h2Splitter; +}; + +#endif diff --git a/examples/widgets/graphicsview/chip/qt4logo.png b/examples/widgets/graphicsview/chip/qt4logo.png Binary files differnew file mode 100644 index 0000000000..157e86ed64 --- /dev/null +++ b/examples/widgets/graphicsview/chip/qt4logo.png diff --git a/examples/widgets/graphicsview/chip/rotateleft.png b/examples/widgets/graphicsview/chip/rotateleft.png Binary files differnew file mode 100644 index 0000000000..8cfa931986 --- /dev/null +++ b/examples/widgets/graphicsview/chip/rotateleft.png diff --git a/examples/widgets/graphicsview/chip/rotateright.png b/examples/widgets/graphicsview/chip/rotateright.png Binary files differnew file mode 100644 index 0000000000..ec5e8664a1 --- /dev/null +++ b/examples/widgets/graphicsview/chip/rotateright.png diff --git a/examples/widgets/graphicsview/chip/view.cpp b/examples/widgets/graphicsview/chip/view.cpp new file mode 100644 index 0000000000..b755b8eadd --- /dev/null +++ b/examples/widgets/graphicsview/chip/view.cpp @@ -0,0 +1,279 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "view.h" + +#include <QtWidgets> +#ifndef QT_NO_PRINTER +#include <QPrinter> +#include <QPrintDialog> +#endif +#ifndef QT_NO_OPENGL +#include <QtOpenGL> +#endif +#include <qmath.h> + +void GraphicsView::wheelEvent(QWheelEvent *e) +{ + if (e->modifiers() & Qt::ControlModifier) { + if (e->delta() > 0) + view->zoomIn(6); + else + view->zoomOut(6); + e->accept(); + } else { + QGraphicsView::wheelEvent(e); + } +} + +View::View(const QString &name, QWidget *parent) + : QFrame(parent) +{ + setFrameStyle(Sunken | StyledPanel); + graphicsView = new GraphicsView(this); + graphicsView->setRenderHint(QPainter::Antialiasing, false); + graphicsView->setDragMode(QGraphicsView::RubberBandDrag); + graphicsView->setOptimizationFlags(QGraphicsView::DontSavePainterState); + graphicsView->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate); + graphicsView->setTransformationAnchor(QGraphicsView::AnchorUnderMouse); + + int size = style()->pixelMetric(QStyle::PM_ToolBarIconSize); + QSize iconSize(size, size); + + QToolButton *zoomInIcon = new QToolButton; + zoomInIcon->setAutoRepeat(true); + zoomInIcon->setAutoRepeatInterval(33); + zoomInIcon->setAutoRepeatDelay(0); + zoomInIcon->setIcon(QPixmap(":/zoomin.png")); + zoomInIcon->setIconSize(iconSize); + QToolButton *zoomOutIcon = new QToolButton; + zoomOutIcon->setAutoRepeat(true); + zoomOutIcon->setAutoRepeatInterval(33); + zoomOutIcon->setAutoRepeatDelay(0); + zoomOutIcon->setIcon(QPixmap(":/zoomout.png")); + zoomOutIcon->setIconSize(iconSize); + zoomSlider = new QSlider; + zoomSlider->setMinimum(0); + zoomSlider->setMaximum(500); + zoomSlider->setValue(250); + zoomSlider->setTickPosition(QSlider::TicksRight); + + // Zoom slider layout + QVBoxLayout *zoomSliderLayout = new QVBoxLayout; + zoomSliderLayout->addWidget(zoomInIcon); + zoomSliderLayout->addWidget(zoomSlider); + zoomSliderLayout->addWidget(zoomOutIcon); + + QToolButton *rotateLeftIcon = new QToolButton; + rotateLeftIcon->setIcon(QPixmap(":/rotateleft.png")); + rotateLeftIcon->setIconSize(iconSize); + QToolButton *rotateRightIcon = new QToolButton; + rotateRightIcon->setIcon(QPixmap(":/rotateright.png")); + rotateRightIcon->setIconSize(iconSize); + rotateSlider = new QSlider; + rotateSlider->setOrientation(Qt::Horizontal); + rotateSlider->setMinimum(-360); + rotateSlider->setMaximum(360); + rotateSlider->setValue(0); + rotateSlider->setTickPosition(QSlider::TicksBelow); + + // Rotate slider layout + QHBoxLayout *rotateSliderLayout = new QHBoxLayout; + rotateSliderLayout->addWidget(rotateLeftIcon); + rotateSliderLayout->addWidget(rotateSlider); + rotateSliderLayout->addWidget(rotateRightIcon); + + resetButton = new QToolButton; + resetButton->setText(tr("0")); + resetButton->setEnabled(false); + + // Label layout + QHBoxLayout *labelLayout = new QHBoxLayout; + label = new QLabel(name); + label2 = new QLabel(tr("Pointer Mode")); + selectModeButton = new QToolButton; + selectModeButton->setText(tr("Select")); + selectModeButton->setCheckable(true); + selectModeButton->setChecked(true); + dragModeButton = new QToolButton; + dragModeButton->setText(tr("Drag")); + dragModeButton->setCheckable(true); + dragModeButton->setChecked(false); + antialiasButton = new QToolButton; + antialiasButton->setText(tr("Antialiasing")); + antialiasButton->setCheckable(true); + antialiasButton->setChecked(false); + openGlButton = new QToolButton; + openGlButton->setText(tr("OpenGL")); + openGlButton->setCheckable(true); +#ifndef QT_NO_OPENGL + openGlButton->setEnabled(QGLFormat::hasOpenGL()); +#else + openGlButton->setEnabled(false); +#endif + printButton = new QToolButton; + printButton->setIcon(QIcon(QPixmap(":/fileprint.png"))); + + QButtonGroup *pointerModeGroup = new QButtonGroup; + pointerModeGroup->setExclusive(true); + pointerModeGroup->addButton(selectModeButton); + pointerModeGroup->addButton(dragModeButton); + + labelLayout->addWidget(label); + labelLayout->addStretch(); + labelLayout->addWidget(label2); + labelLayout->addWidget(selectModeButton); + labelLayout->addWidget(dragModeButton); + labelLayout->addStretch(); + labelLayout->addWidget(antialiasButton); + labelLayout->addWidget(openGlButton); + labelLayout->addWidget(printButton); + + QGridLayout *topLayout = new QGridLayout; + topLayout->addLayout(labelLayout, 0, 0); + topLayout->addWidget(graphicsView, 1, 0); + topLayout->addLayout(zoomSliderLayout, 1, 1); + topLayout->addLayout(rotateSliderLayout, 2, 0); + topLayout->addWidget(resetButton, 2, 1); + setLayout(topLayout); + + connect(resetButton, SIGNAL(clicked()), this, SLOT(resetView())); + connect(zoomSlider, SIGNAL(valueChanged(int)), this, SLOT(setupMatrix())); + connect(rotateSlider, SIGNAL(valueChanged(int)), this, SLOT(setupMatrix())); + connect(graphicsView->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(setResetButtonEnabled())); + connect(graphicsView->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(setResetButtonEnabled())); + connect(selectModeButton, SIGNAL(toggled(bool)), this, SLOT(togglePointerMode())); + connect(dragModeButton, SIGNAL(toggled(bool)), this, SLOT(togglePointerMode())); + connect(antialiasButton, SIGNAL(toggled(bool)), this, SLOT(toggleAntialiasing())); + connect(openGlButton, SIGNAL(toggled(bool)), this, SLOT(toggleOpenGL())); + connect(rotateLeftIcon, SIGNAL(clicked()), this, SLOT(rotateLeft())); + connect(rotateRightIcon, SIGNAL(clicked()), this, SLOT(rotateRight())); + connect(zoomInIcon, SIGNAL(clicked()), this, SLOT(zoomIn())); + connect(zoomOutIcon, SIGNAL(clicked()), this, SLOT(zoomOut())); + connect(printButton, SIGNAL(clicked()), this, SLOT(print())); + + setupMatrix(); +} + +QGraphicsView *View::view() const +{ + return static_cast<QGraphicsView *>(graphicsView); +} + +void View::resetView() +{ + zoomSlider->setValue(250); + rotateSlider->setValue(0); + setupMatrix(); + graphicsView->ensureVisible(QRectF(0, 0, 0, 0)); + + resetButton->setEnabled(false); +} + +void View::setResetButtonEnabled() +{ + resetButton->setEnabled(true); +} + +void View::setupMatrix() +{ + qreal scale = qPow(qreal(2), (zoomSlider->value() - 250) / qreal(50)); + + QMatrix matrix; + matrix.scale(scale, scale); + matrix.rotate(rotateSlider->value()); + + graphicsView->setMatrix(matrix); + setResetButtonEnabled(); +} + +void View::togglePointerMode() +{ + graphicsView->setDragMode(selectModeButton->isChecked() + ? QGraphicsView::RubberBandDrag + : QGraphicsView::ScrollHandDrag); + graphicsView->setInteractive(selectModeButton->isChecked()); +} + +void View::toggleOpenGL() +{ +#ifndef QT_NO_OPENGL + graphicsView->setViewport(openGlButton->isChecked() ? new QGLWidget(QGLFormat(QGL::SampleBuffers)) : new QWidget); +#endif +} + +void View::toggleAntialiasing() +{ + graphicsView->setRenderHint(QPainter::Antialiasing, antialiasButton->isChecked()); +} + +void View::print() +{ +#ifndef QT_NO_PRINTER + QPrinter printer; + QPrintDialog dialog(&printer, this); + if (dialog.exec() == QDialog::Accepted) { + QPainter painter(&printer); + graphicsView->render(&painter); + } +#endif +} + +void View::zoomIn(int level) +{ + zoomSlider->setValue(zoomSlider->value() + level); +} + +void View::zoomOut(int level) +{ + zoomSlider->setValue(zoomSlider->value() - level); +} + +void View::rotateLeft() +{ + rotateSlider->setValue(rotateSlider->value() - 10); +} + +void View::rotateRight() +{ + rotateSlider->setValue(rotateSlider->value() + 10); +} + diff --git a/examples/widgets/graphicsview/chip/view.h b/examples/widgets/graphicsview/chip/view.h new file mode 100644 index 0000000000..7753efff55 --- /dev/null +++ b/examples/widgets/graphicsview/chip/view.h @@ -0,0 +1,104 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef VIEW_H +#define VIEW_H + +#include <QFrame> +#include <QGraphicsView> + +QT_FORWARD_DECLARE_CLASS(QLabel) +QT_FORWARD_DECLARE_CLASS(QSlider) +QT_FORWARD_DECLARE_CLASS(QToolButton) + +class View; + +class GraphicsView : public QGraphicsView +{ + Q_OBJECT +public: + GraphicsView(View *v) : QGraphicsView(), view(v) { } + +protected: + void wheelEvent(QWheelEvent *); + +private: + View *view; +}; + +class View : public QFrame +{ + Q_OBJECT +public: + View(const QString &name, QWidget *parent = 0); + + QGraphicsView *view() const; + +public slots: + void zoomIn(int level = 1); + void zoomOut(int level = 1); + +private slots: + void resetView(); + void setResetButtonEnabled(); + void setupMatrix(); + void togglePointerMode(); + void toggleOpenGL(); + void toggleAntialiasing(); + void print(); + void rotateLeft(); + void rotateRight(); + +private: + GraphicsView *graphicsView; + QLabel *label; + QLabel *label2; + QToolButton *selectModeButton; + QToolButton *dragModeButton; + QToolButton *openGlButton; + QToolButton *antialiasButton; + QToolButton *printButton; + QToolButton *resetButton; + QSlider *zoomSlider; + QSlider *rotateSlider; +}; + +#endif diff --git a/examples/widgets/graphicsview/chip/zoomin.png b/examples/widgets/graphicsview/chip/zoomin.png Binary files differnew file mode 100644 index 0000000000..8b0daeea48 --- /dev/null +++ b/examples/widgets/graphicsview/chip/zoomin.png diff --git a/examples/widgets/graphicsview/chip/zoomout.png b/examples/widgets/graphicsview/chip/zoomout.png Binary files differnew file mode 100644 index 0000000000..1575dd24f6 --- /dev/null +++ b/examples/widgets/graphicsview/chip/zoomout.png diff --git a/examples/widgets/graphicsview/collidingmice/collidingmice.desktop b/examples/widgets/graphicsview/collidingmice/collidingmice.desktop new file mode 100644 index 0000000000..f0064e7112 --- /dev/null +++ b/examples/widgets/graphicsview/collidingmice/collidingmice.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Colliding Mice +Exec=/opt/usr/bin/collidingmice +Icon=collidingmice +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/graphicsview/collidingmice/collidingmice.pro b/examples/widgets/graphicsview/collidingmice/collidingmice.pro new file mode 100644 index 0000000000..d8346023ba --- /dev/null +++ b/examples/widgets/graphicsview/collidingmice/collidingmice.pro @@ -0,0 +1,17 @@ +HEADERS += \ + mouse.h +SOURCES += \ + main.cpp \ + mouse.cpp + +RESOURCES += \ + mice.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/collidingmice +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS collidingmice.pro images +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/collidingmice +INSTALLS += target sources + +QT += widgets + diff --git a/examples/widgets/graphicsview/collidingmice/images/cheese.jpg b/examples/widgets/graphicsview/collidingmice/images/cheese.jpg Binary files differnew file mode 100644 index 0000000000..dea5795fd0 --- /dev/null +++ b/examples/widgets/graphicsview/collidingmice/images/cheese.jpg diff --git a/examples/widgets/graphicsview/collidingmice/main.cpp b/examples/widgets/graphicsview/collidingmice/main.cpp new file mode 100644 index 0000000000..63b14cf075 --- /dev/null +++ b/examples/widgets/graphicsview/collidingmice/main.cpp @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "mouse.h" + +#include <QtWidgets> + +#include <math.h> + +static const int MouseCount = 7; + +//! [0] +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); +//! [0] + +//! [1] + QGraphicsScene scene; + scene.setSceneRect(-300, -300, 600, 600); +//! [1] //! [2] + scene.setItemIndexMethod(QGraphicsScene::NoIndex); +//! [2] + +//! [3] + for (int i = 0; i < MouseCount; ++i) { + Mouse *mouse = new Mouse; + mouse->setPos(::sin((i * 6.28) / MouseCount) * 200, + ::cos((i * 6.28) / MouseCount) * 200); + scene.addItem(mouse); + } +//! [3] + +//! [4] + QGraphicsView view(&scene); + view.setRenderHint(QPainter::Antialiasing); + view.setBackgroundBrush(QPixmap(":/images/cheese.jpg")); +//! [4] //! [5] + view.setCacheMode(QGraphicsView::CacheBackground); + view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); + view.setDragMode(QGraphicsView::ScrollHandDrag); +//! [5] //! [6] + view.setWindowTitle(QT_TRANSLATE_NOOP(QGraphicsView, "Colliding Mice")); + view.resize(400, 300); + view.show(); + + QTimer timer; + QObject::connect(&timer, SIGNAL(timeout()), &scene, SLOT(advance())); + timer.start(1000 / 33); + + return app.exec(); +} +//! [6] diff --git a/examples/widgets/graphicsview/collidingmice/mice.qrc b/examples/widgets/graphicsview/collidingmice/mice.qrc new file mode 100644 index 0000000000..accdb4d0a6 --- /dev/null +++ b/examples/widgets/graphicsview/collidingmice/mice.qrc @@ -0,0 +1,5 @@ +<RCC> + <qresource prefix="/" > + <file>images/cheese.jpg</file> + </qresource> +</RCC> diff --git a/examples/widgets/graphicsview/collidingmice/mouse.cpp b/examples/widgets/graphicsview/collidingmice/mouse.cpp new file mode 100644 index 0000000000..2ffbeff6d5 --- /dev/null +++ b/examples/widgets/graphicsview/collidingmice/mouse.cpp @@ -0,0 +1,200 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "mouse.h" + +#include <QGraphicsScene> +#include <QPainter> +#include <QStyleOption> + +#include <math.h> + +static const double Pi = 3.14159265358979323846264338327950288419717; +static double TwoPi = 2.0 * Pi; + +static qreal normalizeAngle(qreal angle) +{ + while (angle < 0) + angle += TwoPi; + while (angle > TwoPi) + angle -= TwoPi; + return angle; +} + +//! [0] +Mouse::Mouse() + : angle(0), speed(0), mouseEyeDirection(0), + color(qrand() % 256, qrand() % 256, qrand() % 256) +{ + setRotation(qrand() % (360 * 16)); +} +//! [0] + +//! [1] +QRectF Mouse::boundingRect() const +{ + qreal adjust = 0.5; + return QRectF(-18 - adjust, -22 - adjust, + 36 + adjust, 60 + adjust); +} +//! [1] + +//! [2] +QPainterPath Mouse::shape() const +{ + QPainterPath path; + path.addRect(-10, -20, 20, 40); + return path; +} +//! [2] + +//! [3] +void Mouse::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +{ + // Body + painter->setBrush(color); + painter->drawEllipse(-10, -20, 20, 40); + + // Eyes + painter->setBrush(Qt::white); + painter->drawEllipse(-10, -17, 8, 8); + painter->drawEllipse(2, -17, 8, 8); + + // Nose + painter->setBrush(Qt::black); + painter->drawEllipse(QRectF(-2, -22, 4, 4)); + + // Pupils + painter->drawEllipse(QRectF(-8.0 + mouseEyeDirection, -17, 4, 4)); + painter->drawEllipse(QRectF(4.0 + mouseEyeDirection, -17, 4, 4)); + + // Ears + painter->setBrush(scene()->collidingItems(this).isEmpty() ? Qt::darkYellow : Qt::red); + painter->drawEllipse(-17, -12, 16, 16); + painter->drawEllipse(1, -12, 16, 16); + + // Tail + QPainterPath path(QPointF(0, 20)); + path.cubicTo(-5, 22, -5, 22, 0, 25); + path.cubicTo(5, 27, 5, 32, 0, 30); + path.cubicTo(-5, 32, -5, 42, 0, 35); + painter->setBrush(Qt::NoBrush); + painter->drawPath(path); +} +//! [3] + +//! [4] +void Mouse::advance(int step) +{ + if (!step) + return; +//! [4] + // Don't move too far away +//! [5] + QLineF lineToCenter(QPointF(0, 0), mapFromScene(0, 0)); + if (lineToCenter.length() > 150) { + qreal angleToCenter = ::acos(lineToCenter.dx() / lineToCenter.length()); + if (lineToCenter.dy() < 0) + angleToCenter = TwoPi - angleToCenter; + angleToCenter = normalizeAngle((Pi - angleToCenter) + Pi / 2); + + if (angleToCenter < Pi && angleToCenter > Pi / 4) { + // Rotate left + angle += (angle < -Pi / 2) ? 0.25 : -0.25; + } else if (angleToCenter >= Pi && angleToCenter < (Pi + Pi / 2 + Pi / 4)) { + // Rotate right + angle += (angle < Pi / 2) ? 0.25 : -0.25; + } + } else if (::sin(angle) < 0) { + angle += 0.25; + } else if (::sin(angle) > 0) { + angle -= 0.25; +//! [5] //! [6] + } +//! [6] + + // Try not to crash with any other mice +//! [7] + QList<QGraphicsItem *> dangerMice = scene()->items(QPolygonF() + << mapToScene(0, 0) + << mapToScene(-30, -50) + << mapToScene(30, -50)); + foreach (QGraphicsItem *item, dangerMice) { + if (item == this) + continue; + + QLineF lineToMouse(QPointF(0, 0), mapFromItem(item, 0, 0)); + qreal angleToMouse = ::acos(lineToMouse.dx() / lineToMouse.length()); + if (lineToMouse.dy() < 0) + angleToMouse = TwoPi - angleToMouse; + angleToMouse = normalizeAngle((Pi - angleToMouse) + Pi / 2); + + if (angleToMouse >= 0 && angleToMouse < Pi / 2) { + // Rotate right + angle += 0.5; + } else if (angleToMouse <= TwoPi && angleToMouse > (TwoPi - Pi / 2)) { + // Rotate left + angle -= 0.5; +//! [7] //! [8] + } +//! [8] //! [9] + } +//! [9] + + // Add some random movement +//! [10] + if (dangerMice.size() > 1 && (qrand() % 10) == 0) { + if (qrand() % 1) + angle += (qrand() % 100) / 500.0; + else + angle -= (qrand() % 100) / 500.0; + } +//! [10] + +//! [11] + speed += (-50 + qrand() % 100) / 100.0; + + qreal dx = ::sin(angle) * 10; + mouseEyeDirection = (qAbs(dx / 5) < 1) ? 0 : dx / 5; + + setRotation(rotation() + dx); + setPos(mapToParent(0, -(3 + sin(speed) * 3))); +} +//! [11] diff --git a/examples/widgets/graphicsview/collidingmice/mouse.h b/examples/widgets/graphicsview/collidingmice/mouse.h new file mode 100644 index 0000000000..fd036e8b93 --- /dev/null +++ b/examples/widgets/graphicsview/collidingmice/mouse.h @@ -0,0 +1,68 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MOUSE_H +#define MOUSE_H + +#include <QGraphicsItem> + +//! [0] +class Mouse : public QGraphicsItem +{ +public: + Mouse(); + + QRectF boundingRect() const; + QPainterPath shape() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, + QWidget *widget); + +protected: + void advance(int step); + +private: + qreal angle; + qreal speed; + qreal mouseEyeDirection; + QColor color; +}; +//! [0] + +#endif diff --git a/examples/widgets/graphicsview/diagramscene/arrow.cpp b/examples/widgets/graphicsview/diagramscene/arrow.cpp new file mode 100644 index 0000000000..236d836e13 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/arrow.cpp @@ -0,0 +1,145 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> + +#include "arrow.h" +#include <math.h> + +const qreal Pi = 3.14; + +//! [0] +Arrow::Arrow(DiagramItem *startItem, DiagramItem *endItem, QGraphicsItem *parent) + : QGraphicsLineItem(parent) +{ + myStartItem = startItem; + myEndItem = endItem; + setFlag(QGraphicsItem::ItemIsSelectable, true); + myColor = Qt::black; + setPen(QPen(myColor, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); +} +//! [0] + +//! [1] +QRectF Arrow::boundingRect() const +{ + qreal extra = (pen().width() + 20) / 2.0; + + return QRectF(line().p1(), QSizeF(line().p2().x() - line().p1().x(), + line().p2().y() - line().p1().y())) + .normalized() + .adjusted(-extra, -extra, extra, extra); +} +//! [1] + +//! [2] +QPainterPath Arrow::shape() const +{ + QPainterPath path = QGraphicsLineItem::shape(); + path.addPolygon(arrowHead); + return path; +} +//! [2] + +//! [3] +void Arrow::updatePosition() +{ + QLineF line(mapFromItem(myStartItem, 0, 0), mapFromItem(myEndItem, 0, 0)); + setLine(line); +} +//! [3] + +//! [4] +void Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *, + QWidget *) +{ + if (myStartItem->collidesWithItem(myEndItem)) + return; + + QPen myPen = pen(); + myPen.setColor(myColor); + qreal arrowSize = 20; + painter->setPen(myPen); + painter->setBrush(myColor); +//! [4] //! [5] + + QLineF centerLine(myStartItem->pos(), myEndItem->pos()); + QPolygonF endPolygon = myEndItem->polygon(); + QPointF p1 = endPolygon.first() + myEndItem->pos(); + QPointF p2; + QPointF intersectPoint; + QLineF polyLine; + for (int i = 1; i < endPolygon.count(); ++i) { + p2 = endPolygon.at(i) + myEndItem->pos(); + polyLine = QLineF(p1, p2); + QLineF::IntersectType intersectType = + polyLine.intersect(centerLine, &intersectPoint); + if (intersectType == QLineF::BoundedIntersection) + break; + p1 = p2; + } + + setLine(QLineF(intersectPoint, myStartItem->pos())); +//! [5] //! [6] + + double angle = ::acos(line().dx() / line().length()); + if (line().dy() >= 0) + angle = (Pi * 2) - angle; + + QPointF arrowP1 = line().p1() + QPointF(sin(angle + Pi / 3) * arrowSize, + cos(angle + Pi / 3) * arrowSize); + QPointF arrowP2 = line().p1() + QPointF(sin(angle + Pi - Pi / 3) * arrowSize, + cos(angle + Pi - Pi / 3) * arrowSize); + + arrowHead.clear(); + arrowHead << line().p1() << arrowP1 << arrowP2; +//! [6] //! [7] + painter->drawLine(line()); + painter->drawPolygon(arrowHead); + if (isSelected()) { + painter->setPen(QPen(myColor, 1, Qt::DashLine)); + QLineF myLine = line(); + myLine.translate(0, 4.0); + painter->drawLine(myLine); + myLine.translate(0,-8.0); + painter->drawLine(myLine); + } +} +//! [7] diff --git a/examples/widgets/graphicsview/diagramscene/arrow.h b/examples/widgets/graphicsview/diagramscene/arrow.h new file mode 100644 index 0000000000..ac09d6ad00 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/arrow.h @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ARROW_H +#define ARROW_H + +#include <QGraphicsLineItem> + +#include "diagramitem.h" + +QT_BEGIN_NAMESPACE +class QGraphicsPolygonItem; +class QGraphicsLineItem; +class QGraphicsScene; +class QRectF; +class QGraphicsSceneMouseEvent; +class QPainterPath; +QT_END_NAMESPACE + +//! [0] +class Arrow : public QGraphicsLineItem +{ +public: + enum { Type = UserType + 4 }; + + Arrow(DiagramItem *startItem, DiagramItem *endItem, + QGraphicsItem *parent = 0); + + int type() const + { return Type; } + QRectF boundingRect() const; + QPainterPath shape() const; + void setColor(const QColor &color) + { myColor = color; } + DiagramItem *startItem() const + { return myStartItem; } + DiagramItem *endItem() const + { return myEndItem; } + + void updatePosition(); + +protected: + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, + QWidget *widget = 0); + +private: + DiagramItem *myStartItem; + DiagramItem *myEndItem; + QColor myColor; + QPolygonF arrowHead; +}; +//! [0] + +#endif diff --git a/examples/widgets/graphicsview/diagramscene/diagramitem.cpp b/examples/widgets/graphicsview/diagramscene/diagramitem.cpp new file mode 100644 index 0000000000..9509c30270 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/diagramitem.cpp @@ -0,0 +1,152 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> + +#include "diagramitem.h" +#include "arrow.h" + +//! [0] +DiagramItem::DiagramItem(DiagramType diagramType, QMenu *contextMenu, + QGraphicsItem *parent) + : QGraphicsPolygonItem(parent) +{ + myDiagramType = diagramType; + myContextMenu = contextMenu; + + QPainterPath path; + switch (myDiagramType) { + case StartEnd: + path.moveTo(200, 50); + path.arcTo(150, 0, 50, 50, 0, 90); + path.arcTo(50, 0, 50, 50, 90, 90); + path.arcTo(50, 50, 50, 50, 180, 90); + path.arcTo(150, 50, 50, 50, 270, 90); + path.lineTo(200, 25); + myPolygon = path.toFillPolygon(); + break; + case Conditional: + myPolygon << QPointF(-100, 0) << QPointF(0, 100) + << QPointF(100, 0) << QPointF(0, -100) + << QPointF(-100, 0); + break; + case Step: + myPolygon << QPointF(-100, -100) << QPointF(100, -100) + << QPointF(100, 100) << QPointF(-100, 100) + << QPointF(-100, -100); + break; + default: + myPolygon << QPointF(-120, -80) << QPointF(-70, 80) + << QPointF(120, 80) << QPointF(70, -80) + << QPointF(-120, -80); + break; + } + setPolygon(myPolygon); + setFlag(QGraphicsItem::ItemIsMovable, true); + setFlag(QGraphicsItem::ItemIsSelectable, true); + setFlag(QGraphicsItem::ItemSendsGeometryChanges, true); +} +//! [0] + +//! [1] +void DiagramItem::removeArrow(Arrow *arrow) +{ + int index = arrows.indexOf(arrow); + + if (index != -1) + arrows.removeAt(index); +} +//! [1] + +//! [2] +void DiagramItem::removeArrows() +{ + foreach (Arrow *arrow, arrows) { + arrow->startItem()->removeArrow(arrow); + arrow->endItem()->removeArrow(arrow); + scene()->removeItem(arrow); + delete arrow; + } +} +//! [2] + +//! [3] +void DiagramItem::addArrow(Arrow *arrow) +{ + arrows.append(arrow); +} +//! [3] + +//! [4] +QPixmap DiagramItem::image() const +{ + QPixmap pixmap(250, 250); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + painter.setPen(QPen(Qt::black, 8)); + painter.translate(125, 125); + painter.drawPolyline(myPolygon); + + return pixmap; +} +//! [4] + +//! [5] +void DiagramItem::contextMenuEvent(QGraphicsSceneContextMenuEvent *event) +{ + scene()->clearSelection(); + setSelected(true); + myContextMenu->exec(event->screenPos()); +} +//! [5] + +//! [6] +QVariant DiagramItem::itemChange(GraphicsItemChange change, + const QVariant &value) +{ + if (change == QGraphicsItem::ItemPositionChange) { + foreach (Arrow *arrow, arrows) { + arrow->updatePosition(); + } + } + + return value; +} +//! [6] diff --git a/examples/widgets/graphicsview/diagramscene/diagramitem.h b/examples/widgets/graphicsview/diagramscene/diagramitem.h new file mode 100644 index 0000000000..07b3b6e830 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/diagramitem.h @@ -0,0 +1,96 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef DIAGRAMITEM_H +#define DIAGRAMITEM_H + +#include <QGraphicsPixmapItem> +#include <QList> + +QT_BEGIN_NAMESPACE +class QPixmap; +class QGraphicsItem; +class QGraphicsScene; +class QTextEdit; +class QGraphicsSceneMouseEvent; +class QMenu; +class QGraphicsSceneContextMenuEvent; +class QPainter; +class QStyleOptionGraphicsItem; +class QWidget; +class QPolygonF; +QT_END_NAMESPACE + +class Arrow; + +//! [0] +class DiagramItem : public QGraphicsPolygonItem +{ +public: + enum { Type = UserType + 15 }; + enum DiagramType { Step, Conditional, StartEnd, Io }; + + DiagramItem(DiagramType diagramType, QMenu *contextMenu, + QGraphicsItem *parent = 0); + + void removeArrow(Arrow *arrow); + void removeArrows(); + DiagramType diagramType() const + { return myDiagramType; } + QPolygonF polygon() const + { return myPolygon; } + void addArrow(Arrow *arrow); + QPixmap image() const; + int type() const + { return Type;} + +protected: + void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); + QVariant itemChange(GraphicsItemChange change, const QVariant &value); + +private: + DiagramType myDiagramType; + QPolygonF myPolygon; + QMenu *myContextMenu; + QList<Arrow *> arrows; +}; +//! [0] + +#endif diff --git a/examples/widgets/graphicsview/diagramscene/diagramscene.cpp b/examples/widgets/graphicsview/diagramscene/diagramscene.cpp new file mode 100644 index 0000000000..c4a654aa99 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/diagramscene.cpp @@ -0,0 +1,240 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> + +#include "diagramscene.h" +#include "arrow.h" + +//! [0] +DiagramScene::DiagramScene(QMenu *itemMenu, QObject *parent) + : QGraphicsScene(parent) +{ + myItemMenu = itemMenu; + myMode = MoveItem; + myItemType = DiagramItem::Step; + line = 0; + textItem = 0; + myItemColor = Qt::white; + myTextColor = Qt::black; + myLineColor = Qt::black; +} +//! [0] + +//! [1] +void DiagramScene::setLineColor(const QColor &color) +{ + myLineColor = color; + if (isItemChange(Arrow::Type)) { + Arrow *item = + qgraphicsitem_cast<Arrow *>(selectedItems().first()); + item->setColor(myLineColor); + update(); + } +} +//! [1] + +//! [2] +void DiagramScene::setTextColor(const QColor &color) +{ + myTextColor = color; + if (isItemChange(DiagramTextItem::Type)) { + DiagramTextItem *item = + qgraphicsitem_cast<DiagramTextItem *>(selectedItems().first()); + item->setDefaultTextColor(myTextColor); + } +} +//! [2] + +//! [3] +void DiagramScene::setItemColor(const QColor &color) +{ + myItemColor = color; + if (isItemChange(DiagramItem::Type)) { + DiagramItem *item = + qgraphicsitem_cast<DiagramItem *>(selectedItems().first()); + item->setBrush(myItemColor); + } +} +//! [3] + +//! [4] +void DiagramScene::setFont(const QFont &font) +{ + myFont = font; + + if (isItemChange(DiagramTextItem::Type)) { + QGraphicsTextItem *item = + qgraphicsitem_cast<DiagramTextItem *>(selectedItems().first()); + //At this point the selection can change so the first selected item might not be a DiagramTextItem + if (item) + item->setFont(myFont); + } +} +//! [4] + +void DiagramScene::setMode(Mode mode) +{ + myMode = mode; +} + +void DiagramScene::setItemType(DiagramItem::DiagramType type) +{ + myItemType = type; +} + +//! [5] +void DiagramScene::editorLostFocus(DiagramTextItem *item) +{ + QTextCursor cursor = item->textCursor(); + cursor.clearSelection(); + item->setTextCursor(cursor); + + if (item->toPlainText().isEmpty()) { + removeItem(item); + item->deleteLater(); + } +} +//! [5] + +//! [6] +void DiagramScene::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) +{ + if (mouseEvent->button() != Qt::LeftButton) + return; + + DiagramItem *item; + switch (myMode) { + case InsertItem: + item = new DiagramItem(myItemType, myItemMenu); + item->setBrush(myItemColor); + addItem(item); + item->setPos(mouseEvent->scenePos()); + emit itemInserted(item); + break; +//! [6] //! [7] + case InsertLine: + line = new QGraphicsLineItem(QLineF(mouseEvent->scenePos(), + mouseEvent->scenePos())); + line->setPen(QPen(myLineColor, 2)); + addItem(line); + break; +//! [7] //! [8] + case InsertText: + textItem = new DiagramTextItem(); + textItem->setFont(myFont); + textItem->setTextInteractionFlags(Qt::TextEditorInteraction); + textItem->setZValue(1000.0); + connect(textItem, SIGNAL(lostFocus(DiagramTextItem*)), + this, SLOT(editorLostFocus(DiagramTextItem*))); + connect(textItem, SIGNAL(selectedChange(QGraphicsItem*)), + this, SIGNAL(itemSelected(QGraphicsItem*))); + addItem(textItem); + textItem->setDefaultTextColor(myTextColor); + textItem->setPos(mouseEvent->scenePos()); + emit textInserted(textItem); +//! [8] //! [9] + default: + ; + } + QGraphicsScene::mousePressEvent(mouseEvent); +} +//! [9] + +//! [10] +void DiagramScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent) +{ + if (myMode == InsertLine && line != 0) { + QLineF newLine(line->line().p1(), mouseEvent->scenePos()); + line->setLine(newLine); + } else if (myMode == MoveItem) { + QGraphicsScene::mouseMoveEvent(mouseEvent); + } +} +//! [10] + +//! [11] +void DiagramScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent) +{ + if (line != 0 && myMode == InsertLine) { + QList<QGraphicsItem *> startItems = items(line->line().p1()); + if (startItems.count() && startItems.first() == line) + startItems.removeFirst(); + QList<QGraphicsItem *> endItems = items(line->line().p2()); + if (endItems.count() && endItems.first() == line) + endItems.removeFirst(); + + removeItem(line); + delete line; +//! [11] //! [12] + + if (startItems.count() > 0 && endItems.count() > 0 && + startItems.first()->type() == DiagramItem::Type && + endItems.first()->type() == DiagramItem::Type && + startItems.first() != endItems.first()) { + DiagramItem *startItem = + qgraphicsitem_cast<DiagramItem *>(startItems.first()); + DiagramItem *endItem = + qgraphicsitem_cast<DiagramItem *>(endItems.first()); + Arrow *arrow = new Arrow(startItem, endItem); + arrow->setColor(myLineColor); + startItem->addArrow(arrow); + endItem->addArrow(arrow); + arrow->setZValue(-1000.0); + addItem(arrow); + arrow->updatePosition(); + } + } +//! [12] //! [13] + line = 0; + QGraphicsScene::mouseReleaseEvent(mouseEvent); +} +//! [13] + +//! [14] +bool DiagramScene::isItemChange(int type) +{ + foreach (QGraphicsItem *item, selectedItems()) { + if (item->type() == type) + return true; + } + return false; +} +//! [14] diff --git a/examples/widgets/graphicsview/diagramscene/diagramscene.desktop b/examples/widgets/graphicsview/diagramscene/diagramscene.desktop new file mode 100644 index 0000000000..54506ff979 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/diagramscene.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Diagram Scene +Exec=/opt/usr/bin/diagramscene +Icon=diagramscene +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/graphicsview/diagramscene/diagramscene.h b/examples/widgets/graphicsview/diagramscene/diagramscene.h new file mode 100644 index 0000000000..9f65eba890 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/diagramscene.h @@ -0,0 +1,112 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef DIAGRAMSCENE_H +#define DIAGRAMSCENE_H + +#include <QGraphicsScene> +#include "diagramitem.h" +#include "diagramtextitem.h" + +QT_BEGIN_NAMESPACE +class QGraphicsSceneMouseEvent; +class QMenu; +class QPointF; +class QGraphicsLineItem; +class QFont; +class QGraphicsTextItem; +class QColor; +QT_END_NAMESPACE + +//! [0] +class DiagramScene : public QGraphicsScene +{ + Q_OBJECT + +public: + enum Mode { InsertItem, InsertLine, InsertText, MoveItem }; + + DiagramScene(QMenu *itemMenu, QObject *parent = 0); + QFont font() const + { return myFont; } + QColor textColor() const + { return myTextColor; } + QColor itemColor() const + { return myItemColor; } + QColor lineColor() const + { return myLineColor; } + void setLineColor(const QColor &color); + void setTextColor(const QColor &color); + void setItemColor(const QColor &color); + void setFont(const QFont &font); + +public slots: + void setMode(Mode mode); + void setItemType(DiagramItem::DiagramType type); + void editorLostFocus(DiagramTextItem *item); + +signals: + void itemInserted(DiagramItem *item); + void textInserted(QGraphicsTextItem *item); + void itemSelected(QGraphicsItem *item); + +protected: + void mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent); + void mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent); + +private: + bool isItemChange(int type); + + DiagramItem::DiagramType myItemType; + QMenu *myItemMenu; + Mode myMode; + bool leftButtonDown; + QPointF startPoint; + QGraphicsLineItem *line; + QFont myFont; + DiagramTextItem *textItem; + QColor myTextColor; + QColor myItemColor; + QColor myLineColor; +}; +//! [0] + +#endif diff --git a/examples/widgets/graphicsview/diagramscene/diagramscene.pro b/examples/widgets/graphicsview/diagramscene/diagramscene.pro new file mode 100644 index 0000000000..e45f4a894b --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/diagramscene.pro @@ -0,0 +1,23 @@ +HEADERS = mainwindow.h \ + diagramitem.h \ + diagramscene.h \ + arrow.h \ + diagramtextitem.h +SOURCES = mainwindow.cpp \ + diagramitem.cpp \ + main.cpp \ + arrow.cpp \ + diagramtextitem.cpp \ + diagramscene.cpp +RESOURCES = diagramscene.qrc + + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/diagramscene +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS diagramscene.pro images +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/diagramscene +INSTALLS += target sources + + +QT += widgets +simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/graphicsview/diagramscene/diagramscene.qrc b/examples/widgets/graphicsview/diagramscene/diagramscene.qrc new file mode 100644 index 0000000000..a11158402f --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/diagramscene.qrc @@ -0,0 +1,20 @@ +<!DOCTYPE RCC><RCC version="1.0"> +<qresource> + <file>images/pointer.png</file> + <file>images/linepointer.png</file> + <file>images/textpointer.png</file> + <file>images/bold.png</file> + <file>images/italic.png</file> + <file>images/underline.png</file> + <file>images/floodfill.png</file> + <file>images/bringtofront.png</file> + <file>images/delete.png</file> + <file>images/sendtoback.png</file> + <file>images/linecolor.png</file> + <file>images/background1.png</file> + <file>images/background2.png</file> + <file>images/background3.png</file> + <file>images/background4.png</file> +</qresource> +</RCC> + diff --git a/examples/widgets/graphicsview/diagramscene/diagramtextitem.cpp b/examples/widgets/graphicsview/diagramscene/diagramtextitem.cpp new file mode 100644 index 0000000000..1e583045da --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/diagramtextitem.cpp @@ -0,0 +1,81 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> + +#include "diagramtextitem.h" +#include "diagramscene.h" + +//! [0] +DiagramTextItem::DiagramTextItem(QGraphicsItem *parent) + : QGraphicsTextItem(parent) +{ + setFlag(QGraphicsItem::ItemIsMovable); + setFlag(QGraphicsItem::ItemIsSelectable); +} +//! [0] + +//! [1] +QVariant DiagramTextItem::itemChange(GraphicsItemChange change, + const QVariant &value) +{ + if (change == QGraphicsItem::ItemSelectedHasChanged) + emit selectedChange(this); + return value; +} +//! [1] + +//! [2] +void DiagramTextItem::focusOutEvent(QFocusEvent *event) +{ + setTextInteractionFlags(Qt::NoTextInteraction); + emit lostFocus(this); + QGraphicsTextItem::focusOutEvent(event); +} +//! [2] + +//! [5] +void DiagramTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) +{ + if (textInteractionFlags() == Qt::NoTextInteraction) + setTextInteractionFlags(Qt::TextEditorInteraction); + QGraphicsTextItem::mouseDoubleClickEvent(event); +} +//! [5] diff --git a/examples/widgets/graphicsview/diagramscene/diagramtextitem.h b/examples/widgets/graphicsview/diagramscene/diagramtextitem.h new file mode 100644 index 0000000000..611e9b6700 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/diagramtextitem.h @@ -0,0 +1,78 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef DIAGRAMTEXTITEM_H +#define DIAGRAMTEXTITEM_H + +#include <QGraphicsTextItem> +#include <QPen> + +QT_BEGIN_NAMESPACE +class QFocusEvent; +class QGraphicsItem; +class QGraphicsScene; +class QGraphicsSceneMouseEvent; +QT_END_NAMESPACE + +//! [0] +class DiagramTextItem : public QGraphicsTextItem +{ + Q_OBJECT + +public: + enum { Type = UserType + 3 }; + + DiagramTextItem(QGraphicsItem *parent = 0); + + int type() const + { return Type; } + +signals: + void lostFocus(DiagramTextItem *item); + void selectedChange(QGraphicsItem *item); + +protected: + QVariant itemChange(GraphicsItemChange change, const QVariant &value); + void focusOutEvent(QFocusEvent *event); + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); +}; +//! [0] + +#endif diff --git a/examples/widgets/graphicsview/diagramscene/images/background1.png b/examples/widgets/graphicsview/diagramscene/images/background1.png Binary files differnew file mode 100644 index 0000000000..0f93c6bf42 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/background1.png diff --git a/examples/widgets/graphicsview/diagramscene/images/background2.png b/examples/widgets/graphicsview/diagramscene/images/background2.png Binary files differnew file mode 100644 index 0000000000..1e293db67a --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/background2.png diff --git a/examples/widgets/graphicsview/diagramscene/images/background3.png b/examples/widgets/graphicsview/diagramscene/images/background3.png Binary files differnew file mode 100644 index 0000000000..3db4f8ea5f --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/background3.png diff --git a/examples/widgets/graphicsview/diagramscene/images/background4.png b/examples/widgets/graphicsview/diagramscene/images/background4.png Binary files differnew file mode 100644 index 0000000000..9c1f3bfd77 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/background4.png diff --git a/examples/widgets/graphicsview/diagramscene/images/bold.png b/examples/widgets/graphicsview/diagramscene/images/bold.png Binary files differnew file mode 100644 index 0000000000..986e65e250 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/bold.png diff --git a/examples/widgets/graphicsview/diagramscene/images/bringtofront.png b/examples/widgets/graphicsview/diagramscene/images/bringtofront.png Binary files differnew file mode 100644 index 0000000000..bda27578a2 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/bringtofront.png diff --git a/examples/widgets/graphicsview/diagramscene/images/delete.png b/examples/widgets/graphicsview/diagramscene/images/delete.png Binary files differnew file mode 100644 index 0000000000..df2a147d24 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/delete.png diff --git a/examples/widgets/graphicsview/diagramscene/images/floodfill.png b/examples/widgets/graphicsview/diagramscene/images/floodfill.png Binary files differnew file mode 100644 index 0000000000..54c0dae237 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/floodfill.png diff --git a/examples/widgets/graphicsview/diagramscene/images/italic.png b/examples/widgets/graphicsview/diagramscene/images/italic.png Binary files differnew file mode 100644 index 0000000000..9a438b57ad --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/italic.png diff --git a/examples/widgets/graphicsview/diagramscene/images/linecolor.png b/examples/widgets/graphicsview/diagramscene/images/linecolor.png Binary files differnew file mode 100644 index 0000000000..98a821f27e --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/linecolor.png diff --git a/examples/widgets/graphicsview/diagramscene/images/linepointer.png b/examples/widgets/graphicsview/diagramscene/images/linepointer.png Binary files differnew file mode 100644 index 0000000000..66933d43b3 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/linepointer.png diff --git a/examples/widgets/graphicsview/diagramscene/images/pointer.png b/examples/widgets/graphicsview/diagramscene/images/pointer.png Binary files differnew file mode 100644 index 0000000000..0b0b0aa69d --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/pointer.png diff --git a/examples/widgets/graphicsview/diagramscene/images/sendtoback.png b/examples/widgets/graphicsview/diagramscene/images/sendtoback.png Binary files differnew file mode 100644 index 0000000000..5aa3b0a243 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/sendtoback.png diff --git a/examples/widgets/graphicsview/diagramscene/images/textpointer.png b/examples/widgets/graphicsview/diagramscene/images/textpointer.png Binary files differnew file mode 100644 index 0000000000..b25832cada --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/textpointer.png diff --git a/examples/widgets/graphicsview/diagramscene/images/underline.png b/examples/widgets/graphicsview/diagramscene/images/underline.png Binary files differnew file mode 100644 index 0000000000..9b8209f525 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/images/underline.png diff --git a/examples/widgets/graphicsview/diagramscene/main.cpp b/examples/widgets/graphicsview/diagramscene/main.cpp new file mode 100644 index 0000000000..33bc97b71f --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/main.cpp @@ -0,0 +1,55 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> + +#include "mainwindow.h" + +int main(int argv, char *args[]) +{ + Q_INIT_RESOURCE(diagramscene); + + QApplication app(argv, args); + MainWindow mainWindow; + mainWindow.setGeometry(100, 100, 800, 500); + mainWindow.show(); + + return app.exec(); +} diff --git a/examples/widgets/graphicsview/diagramscene/mainwindow.cpp b/examples/widgets/graphicsview/diagramscene/mainwindow.cpp new file mode 100644 index 0000000000..977730a3bb --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/mainwindow.cpp @@ -0,0 +1,661 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> +#include <QLabel> + +#include "mainwindow.h" +#include "diagramitem.h" +#include "diagramscene.h" +#include "diagramtextitem.h" +#include "arrow.h" + +const int InsertTextButton = 10; + +//! [0] +MainWindow::MainWindow() +{ + createActions(); + createToolBox(); + createMenus(); + + scene = new DiagramScene(itemMenu, this); + scene->setSceneRect(QRectF(0, 0, 5000, 5000)); + connect(scene, SIGNAL(itemInserted(DiagramItem*)), + this, SLOT(itemInserted(DiagramItem*))); + connect(scene, SIGNAL(textInserted(QGraphicsTextItem*)), + this, SLOT(textInserted(QGraphicsTextItem*))); + connect(scene, SIGNAL(itemSelected(QGraphicsItem*)), + this, SLOT(itemSelected(QGraphicsItem*))); + createToolbars(); + + QHBoxLayout *layout = new QHBoxLayout; + layout->addWidget(toolBox); + view = new QGraphicsView(scene); + layout->addWidget(view); + + QWidget *widget = new QWidget; + widget->setLayout(layout); + + setCentralWidget(widget); + setWindowTitle(tr("Diagramscene")); + setUnifiedTitleAndToolBarOnMac(true); +} +//! [0] + +//! [1] +void MainWindow::backgroundButtonGroupClicked(QAbstractButton *button) +{ + QList<QAbstractButton *> buttons = backgroundButtonGroup->buttons(); + foreach (QAbstractButton *myButton, buttons) { + if (myButton != button) + button->setChecked(false); + } + QString text = button->text(); + if (text == tr("Blue Grid")) + scene->setBackgroundBrush(QPixmap(":/images/background1.png")); + else if (text == tr("White Grid")) + scene->setBackgroundBrush(QPixmap(":/images/background2.png")); + else if (text == tr("Gray Grid")) + scene->setBackgroundBrush(QPixmap(":/images/background3.png")); + else + scene->setBackgroundBrush(QPixmap(":/images/background4.png")); + + scene->update(); + view->update(); +} +//! [1] + +//! [2] +void MainWindow::buttonGroupClicked(int id) +{ + QList<QAbstractButton *> buttons = buttonGroup->buttons(); + foreach (QAbstractButton *button, buttons) { + if (buttonGroup->button(id) != button) + button->setChecked(false); + } + if (id == InsertTextButton) { + scene->setMode(DiagramScene::InsertText); + } else { + scene->setItemType(DiagramItem::DiagramType(id)); + scene->setMode(DiagramScene::InsertItem); + } +} +//! [2] + +//! [3] +void MainWindow::deleteItem() +{ + foreach (QGraphicsItem *item, scene->selectedItems()) { + if (item->type() == Arrow::Type) { + scene->removeItem(item); + Arrow *arrow = qgraphicsitem_cast<Arrow *>(item); + arrow->startItem()->removeArrow(arrow); + arrow->endItem()->removeArrow(arrow); + delete item; + } + } + + foreach (QGraphicsItem *item, scene->selectedItems()) { + if (item->type() == DiagramItem::Type) { + qgraphicsitem_cast<DiagramItem *>(item)->removeArrows(); + } + scene->removeItem(item); + delete item; + } +} +//! [3] + +//! [4] +void MainWindow::pointerGroupClicked(int) +{ + scene->setMode(DiagramScene::Mode(pointerTypeGroup->checkedId())); +} +//! [4] + +//! [5] +void MainWindow::bringToFront() +{ + if (scene->selectedItems().isEmpty()) + return; + + QGraphicsItem *selectedItem = scene->selectedItems().first(); + QList<QGraphicsItem *> overlapItems = selectedItem->collidingItems(); + + qreal zValue = 0; + foreach (QGraphicsItem *item, overlapItems) { + if (item->zValue() >= zValue && + item->type() == DiagramItem::Type) + zValue = item->zValue() + 0.1; + } + selectedItem->setZValue(zValue); +} +//! [5] + +//! [6] +void MainWindow::sendToBack() +{ + if (scene->selectedItems().isEmpty()) + return; + + QGraphicsItem *selectedItem = scene->selectedItems().first(); + QList<QGraphicsItem *> overlapItems = selectedItem->collidingItems(); + + qreal zValue = 0; + foreach (QGraphicsItem *item, overlapItems) { + if (item->zValue() <= zValue && + item->type() == DiagramItem::Type) + zValue = item->zValue() - 0.1; + } + selectedItem->setZValue(zValue); +} +//! [6] + +//! [7] +void MainWindow::itemInserted(DiagramItem *item) +{ + pointerTypeGroup->button(int(DiagramScene::MoveItem))->setChecked(true); + scene->setMode(DiagramScene::Mode(pointerTypeGroup->checkedId())); + buttonGroup->button(int(item->diagramType()))->setChecked(false); +} +//! [7] + +//! [8] +void MainWindow::textInserted(QGraphicsTextItem *) +{ + buttonGroup->button(InsertTextButton)->setChecked(false); + scene->setMode(DiagramScene::Mode(pointerTypeGroup->checkedId())); +} +//! [8] + +//! [9] +void MainWindow::currentFontChanged(const QFont &) +{ + handleFontChange(); +} +//! [9] + +//! [10] +void MainWindow::fontSizeChanged(const QString &) +{ + handleFontChange(); +} +//! [10] + +//! [11] +void MainWindow::sceneScaleChanged(const QString &scale) +{ + double newScale = scale.left(scale.indexOf(tr("%"))).toDouble() / 100.0; + QMatrix oldMatrix = view->matrix(); + view->resetMatrix(); + view->translate(oldMatrix.dx(), oldMatrix.dy()); + view->scale(newScale, newScale); +} +//! [11] + +//! [12] +void MainWindow::textColorChanged() +{ + textAction = qobject_cast<QAction *>(sender()); + fontColorToolButton->setIcon(createColorToolButtonIcon( + ":/images/textpointer.png", + qvariant_cast<QColor>(textAction->data()))); + textButtonTriggered(); +} +//! [12] + +//! [13] +void MainWindow::itemColorChanged() +{ + fillAction = qobject_cast<QAction *>(sender()); + fillColorToolButton->setIcon(createColorToolButtonIcon( + ":/images/floodfill.png", + qvariant_cast<QColor>(fillAction->data()))); + fillButtonTriggered(); +} +//! [13] + +//! [14] +void MainWindow::lineColorChanged() +{ + lineAction = qobject_cast<QAction *>(sender()); + lineColorToolButton->setIcon(createColorToolButtonIcon( + ":/images/linecolor.png", + qvariant_cast<QColor>(lineAction->data()))); + lineButtonTriggered(); +} +//! [14] + +//! [15] +void MainWindow::textButtonTriggered() +{ + scene->setTextColor(qvariant_cast<QColor>(textAction->data())); +} +//! [15] + +//! [16] +void MainWindow::fillButtonTriggered() +{ + scene->setItemColor(qvariant_cast<QColor>(fillAction->data())); +} +//! [16] + +//! [17] +void MainWindow::lineButtonTriggered() +{ + scene->setLineColor(qvariant_cast<QColor>(lineAction->data())); +} +//! [17] + +//! [18] +void MainWindow::handleFontChange() +{ + QFont font = fontCombo->currentFont(); + font.setPointSize(fontSizeCombo->currentText().toInt()); + font.setWeight(boldAction->isChecked() ? QFont::Bold : QFont::Normal); + font.setItalic(italicAction->isChecked()); + font.setUnderline(underlineAction->isChecked()); + + scene->setFont(font); +} +//! [18] + +//! [19] +void MainWindow::itemSelected(QGraphicsItem *item) +{ + DiagramTextItem *textItem = + qgraphicsitem_cast<DiagramTextItem *>(item); + + QFont font = textItem->font(); + fontCombo->setCurrentFont(font); + fontSizeCombo->setEditText(QString().setNum(font.pointSize())); + boldAction->setChecked(font.weight() == QFont::Bold); + italicAction->setChecked(font.italic()); + underlineAction->setChecked(font.underline()); +} +//! [19] + +//! [20] +void MainWindow::about() +{ + QMessageBox::about(this, tr("About Diagram Scene"), + tr("The <b>Diagram Scene</b> example shows " + "use of the graphics framework.")); +} +//! [20] + +//! [21] +void MainWindow::createToolBox() +{ + buttonGroup = new QButtonGroup(this); + buttonGroup->setExclusive(false); + connect(buttonGroup, SIGNAL(buttonClicked(int)), + this, SLOT(buttonGroupClicked(int))); + QGridLayout *layout = new QGridLayout; + layout->addWidget(createCellWidget(tr("Conditional"), + DiagramItem::Conditional), 0, 0); + layout->addWidget(createCellWidget(tr("Process"), + DiagramItem::Step),0, 1); + layout->addWidget(createCellWidget(tr("Input/Output"), + DiagramItem::Io), 1, 0); +//! [21] + + QToolButton *textButton = new QToolButton; + textButton->setCheckable(true); + buttonGroup->addButton(textButton, InsertTextButton); + textButton->setIcon(QIcon(QPixmap(":/images/textpointer.png") + .scaled(30, 30))); + textButton->setIconSize(QSize(50, 50)); + QGridLayout *textLayout = new QGridLayout; + textLayout->addWidget(textButton, 0, 0, Qt::AlignHCenter); + textLayout->addWidget(new QLabel(tr("Text")), 1, 0, Qt::AlignCenter); + QWidget *textWidget = new QWidget; + textWidget->setLayout(textLayout); + layout->addWidget(textWidget, 1, 1); + + layout->setRowStretch(3, 10); + layout->setColumnStretch(2, 10); + + QWidget *itemWidget = new QWidget; + itemWidget->setLayout(layout); + + backgroundButtonGroup = new QButtonGroup(this); + connect(backgroundButtonGroup, SIGNAL(buttonClicked(QAbstractButton*)), + this, SLOT(backgroundButtonGroupClicked(QAbstractButton*))); + + QGridLayout *backgroundLayout = new QGridLayout; + backgroundLayout->addWidget(createBackgroundCellWidget(tr("Blue Grid"), + ":/images/background1.png"), 0, 0); + backgroundLayout->addWidget(createBackgroundCellWidget(tr("White Grid"), + ":/images/background2.png"), 0, 1); + backgroundLayout->addWidget(createBackgroundCellWidget(tr("Gray Grid"), + ":/images/background3.png"), 1, 0); + backgroundLayout->addWidget(createBackgroundCellWidget(tr("No Grid"), + ":/images/background4.png"), 1, 1); + + backgroundLayout->setRowStretch(2, 10); + backgroundLayout->setColumnStretch(2, 10); + + QWidget *backgroundWidget = new QWidget; + backgroundWidget->setLayout(backgroundLayout); + + +//! [22] + toolBox = new QToolBox; + toolBox->setSizePolicy(QSizePolicy(QSizePolicy::Maximum, QSizePolicy::Ignored)); + toolBox->setMinimumWidth(itemWidget->sizeHint().width()); + toolBox->addItem(itemWidget, tr("Basic Flowchart Shapes")); + toolBox->addItem(backgroundWidget, tr("Backgrounds")); +} +//! [22] + +//! [23] +void MainWindow::createActions() +{ + toFrontAction = new QAction(QIcon(":/images/bringtofront.png"), + tr("Bring to &Front"), this); + toFrontAction->setShortcut(tr("Ctrl+F")); + toFrontAction->setStatusTip(tr("Bring item to front")); + connect(toFrontAction, SIGNAL(triggered()), + this, SLOT(bringToFront())); +//! [23] + + sendBackAction = new QAction(QIcon(":/images/sendtoback.png"), + tr("Send to &Back"), this); + sendBackAction->setShortcut(tr("Ctrl+B")); + sendBackAction->setStatusTip(tr("Send item to back")); + connect(sendBackAction, SIGNAL(triggered()), + this, SLOT(sendToBack())); + + deleteAction = new QAction(QIcon(":/images/delete.png"), + tr("&Delete"), this); + deleteAction->setShortcut(tr("Delete")); + deleteAction->setStatusTip(tr("Delete item from diagram")); + connect(deleteAction, SIGNAL(triggered()), + this, SLOT(deleteItem())); + + exitAction = new QAction(tr("E&xit"), this); + exitAction->setShortcuts(QKeySequence::Quit); + exitAction->setStatusTip(tr("Quit Scenediagram example")); + connect(exitAction, SIGNAL(triggered()), this, SLOT(close())); + + boldAction = new QAction(tr("Bold"), this); + boldAction->setCheckable(true); + QPixmap pixmap(":/images/bold.png"); + boldAction->setIcon(QIcon(pixmap)); + boldAction->setShortcut(tr("Ctrl+B")); + connect(boldAction, SIGNAL(triggered()), + this, SLOT(handleFontChange())); + + italicAction = new QAction(QIcon(":/images/italic.png"), + tr("Italic"), this); + italicAction->setCheckable(true); + italicAction->setShortcut(tr("Ctrl+I")); + connect(italicAction, SIGNAL(triggered()), + this, SLOT(handleFontChange())); + + underlineAction = new QAction(QIcon(":/images/underline.png"), + tr("Underline"), this); + underlineAction->setCheckable(true); + underlineAction->setShortcut(tr("Ctrl+U")); + connect(underlineAction, SIGNAL(triggered()), + this, SLOT(handleFontChange())); + + aboutAction = new QAction(tr("A&bout"), this); + aboutAction->setShortcut(tr("Ctrl+B")); + connect(aboutAction, SIGNAL(triggered()), + this, SLOT(about())); +} + +//! [24] +void MainWindow::createMenus() +{ + fileMenu = menuBar()->addMenu(tr("&File")); + fileMenu->addAction(exitAction); + + itemMenu = menuBar()->addMenu(tr("&Item")); + itemMenu->addAction(deleteAction); + itemMenu->addSeparator(); + itemMenu->addAction(toFrontAction); + itemMenu->addAction(sendBackAction); + + aboutMenu = menuBar()->addMenu(tr("&Help")); + aboutMenu->addAction(aboutAction); +} +//! [24] + +//! [25] +void MainWindow::createToolbars() +{ +//! [25] + editToolBar = addToolBar(tr("Edit")); + editToolBar->addAction(deleteAction); + editToolBar->addAction(toFrontAction); + editToolBar->addAction(sendBackAction); + + fontCombo = new QFontComboBox(); + connect(fontCombo, SIGNAL(currentFontChanged(QFont)), + this, SLOT(currentFontChanged(QFont))); + + fontSizeCombo = new QComboBox; + fontSizeCombo->setEditable(true); + for (int i = 8; i < 30; i = i + 2) + fontSizeCombo->addItem(QString().setNum(i)); + QIntValidator *validator = new QIntValidator(2, 64, this); + fontSizeCombo->setValidator(validator); + connect(fontSizeCombo, SIGNAL(currentIndexChanged(QString)), + this, SLOT(fontSizeChanged(QString))); + + fontColorToolButton = new QToolButton; + fontColorToolButton->setPopupMode(QToolButton::MenuButtonPopup); + fontColorToolButton->setMenu(createColorMenu(SLOT(textColorChanged()), + Qt::black)); + textAction = fontColorToolButton->menu()->defaultAction(); + fontColorToolButton->setIcon(createColorToolButtonIcon( + ":/images/textpointer.png", Qt::black)); + fontColorToolButton->setAutoFillBackground(true); + connect(fontColorToolButton, SIGNAL(clicked()), + this, SLOT(textButtonTriggered())); + +//! [26] + fillColorToolButton = new QToolButton; + fillColorToolButton->setPopupMode(QToolButton::MenuButtonPopup); + fillColorToolButton->setMenu(createColorMenu(SLOT(itemColorChanged()), + Qt::white)); + fillAction = fillColorToolButton->menu()->defaultAction(); + fillColorToolButton->setIcon(createColorToolButtonIcon( + ":/images/floodfill.png", Qt::white)); + connect(fillColorToolButton, SIGNAL(clicked()), + this, SLOT(fillButtonTriggered())); +//! [26] + + lineColorToolButton = new QToolButton; + lineColorToolButton->setPopupMode(QToolButton::MenuButtonPopup); + lineColorToolButton->setMenu(createColorMenu(SLOT(lineColorChanged()), + Qt::black)); + lineAction = lineColorToolButton->menu()->defaultAction(); + lineColorToolButton->setIcon(createColorToolButtonIcon( + ":/images/linecolor.png", Qt::black)); + connect(lineColorToolButton, SIGNAL(clicked()), + this, SLOT(lineButtonTriggered())); + + textToolBar = addToolBar(tr("Font")); + textToolBar->addWidget(fontCombo); + textToolBar->addWidget(fontSizeCombo); + textToolBar->addAction(boldAction); + textToolBar->addAction(italicAction); + textToolBar->addAction(underlineAction); + + colorToolBar = addToolBar(tr("Color")); + colorToolBar->addWidget(fontColorToolButton); + colorToolBar->addWidget(fillColorToolButton); + colorToolBar->addWidget(lineColorToolButton); + + QToolButton *pointerButton = new QToolButton; + pointerButton->setCheckable(true); + pointerButton->setChecked(true); + pointerButton->setIcon(QIcon(":/images/pointer.png")); + QToolButton *linePointerButton = new QToolButton; + linePointerButton->setCheckable(true); + linePointerButton->setIcon(QIcon(":/images/linepointer.png")); + + pointerTypeGroup = new QButtonGroup(this); + pointerTypeGroup->addButton(pointerButton, int(DiagramScene::MoveItem)); + pointerTypeGroup->addButton(linePointerButton, + int(DiagramScene::InsertLine)); + connect(pointerTypeGroup, SIGNAL(buttonClicked(int)), + this, SLOT(pointerGroupClicked(int))); + + sceneScaleCombo = new QComboBox; + QStringList scales; + scales << tr("50%") << tr("75%") << tr("100%") << tr("125%") << tr("150%"); + sceneScaleCombo->addItems(scales); + sceneScaleCombo->setCurrentIndex(2); + connect(sceneScaleCombo, SIGNAL(currentIndexChanged(QString)), + this, SLOT(sceneScaleChanged(QString))); + + pointerToolbar = addToolBar(tr("Pointer type")); + pointerToolbar->addWidget(pointerButton); + pointerToolbar->addWidget(linePointerButton); + pointerToolbar->addWidget(sceneScaleCombo); +//! [27] +} +//! [27] + +//! [28] +QWidget *MainWindow::createBackgroundCellWidget(const QString &text, + const QString &image) +{ + QToolButton *button = new QToolButton; + button->setText(text); + button->setIcon(QIcon(image)); + button->setIconSize(QSize(50, 50)); + button->setCheckable(true); + backgroundButtonGroup->addButton(button); + + QGridLayout *layout = new QGridLayout; + layout->addWidget(button, 0, 0, Qt::AlignHCenter); + layout->addWidget(new QLabel(text), 1, 0, Qt::AlignCenter); + + QWidget *widget = new QWidget; + widget->setLayout(layout); + + return widget; +} +//! [28] + +//! [29] +QWidget *MainWindow::createCellWidget(const QString &text, + DiagramItem::DiagramType type) +{ + + DiagramItem item(type, itemMenu); + QIcon icon(item.image()); + + QToolButton *button = new QToolButton; + button->setIcon(icon); + button->setIconSize(QSize(50, 50)); + button->setCheckable(true); + buttonGroup->addButton(button, int(type)); + + QGridLayout *layout = new QGridLayout; + layout->addWidget(button, 0, 0, Qt::AlignHCenter); + layout->addWidget(new QLabel(text), 1, 0, Qt::AlignCenter); + + QWidget *widget = new QWidget; + widget->setLayout(layout); + + return widget; +} +//! [29] + +//! [30] +QMenu *MainWindow::createColorMenu(const char *slot, QColor defaultColor) +{ + QList<QColor> colors; + colors << Qt::black << Qt::white << Qt::red << Qt::blue << Qt::yellow; + QStringList names; + names << tr("black") << tr("white") << tr("red") << tr("blue") + << tr("yellow"); + + QMenu *colorMenu = new QMenu(this); + for (int i = 0; i < colors.count(); ++i) { + QAction *action = new QAction(names.at(i), this); + action->setData(colors.at(i)); + action->setIcon(createColorIcon(colors.at(i))); + connect(action, SIGNAL(triggered()), + this, slot); + colorMenu->addAction(action); + if (colors.at(i) == defaultColor) { + colorMenu->setDefaultAction(action); + } + } + return colorMenu; +} +//! [30] + +//! [31] +QIcon MainWindow::createColorToolButtonIcon(const QString &imageFile, + QColor color) +{ + QPixmap pixmap(50, 80); + pixmap.fill(Qt::transparent); + QPainter painter(&pixmap); + QPixmap image(imageFile); + QRect target(0, 0, 50, 60); + QRect source(0, 0, 42, 42); + painter.fillRect(QRect(0, 60, 50, 80), color); + painter.drawPixmap(target, image, source); + + return QIcon(pixmap); +} +//! [31] + +//! [32] +QIcon MainWindow::createColorIcon(QColor color) +{ + QPixmap pixmap(20, 20); + QPainter painter(&pixmap); + painter.setPen(Qt::NoPen); + painter.fillRect(QRect(0, 0, 20, 20), color); + + return QIcon(pixmap); +} +//! [32] diff --git a/examples/widgets/graphicsview/diagramscene/mainwindow.h b/examples/widgets/graphicsview/diagramscene/mainwindow.h new file mode 100644 index 0000000000..e3c0496c79 --- /dev/null +++ b/examples/widgets/graphicsview/diagramscene/mainwindow.h @@ -0,0 +1,150 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include <QMainWindow> + +#include "diagramitem.h" + +class DiagramScene; + +QT_BEGIN_NAMESPACE +class QAction; +class QToolBox; +class QSpinBox; +class QComboBox; +class QFontComboBox; +class QButtonGroup; +class QLineEdit; +class QGraphicsTextItem; +class QFont; +class QToolButton; +class QAbstractButton; +class QGraphicsView; +QT_END_NAMESPACE + +//! [0] +class MainWindow : public QMainWindow +{ + Q_OBJECT + +public: + MainWindow(); + +private slots: + void backgroundButtonGroupClicked(QAbstractButton *button); + void buttonGroupClicked(int id); + void deleteItem(); + void pointerGroupClicked(int id); + void bringToFront(); + void sendToBack(); + void itemInserted(DiagramItem *item); + void textInserted(QGraphicsTextItem *item); + void currentFontChanged(const QFont &font); + void fontSizeChanged(const QString &size); + void sceneScaleChanged(const QString &scale); + void textColorChanged(); + void itemColorChanged(); + void lineColorChanged(); + void textButtonTriggered(); + void fillButtonTriggered(); + void lineButtonTriggered(); + void handleFontChange(); + void itemSelected(QGraphicsItem *item); + void about(); + +private: + void createToolBox(); + void createActions(); + void createMenus(); + void createToolbars(); + QWidget *createBackgroundCellWidget(const QString &text, + const QString &image); + QWidget *createCellWidget(const QString &text, + DiagramItem::DiagramType type); + QMenu *createColorMenu(const char *slot, QColor defaultColor); + QIcon createColorToolButtonIcon(const QString &image, QColor color); + QIcon createColorIcon(QColor color); + + DiagramScene *scene; + QGraphicsView *view; + + QAction *exitAction; + QAction *addAction; + QAction *deleteAction; + + QAction *toFrontAction; + QAction *sendBackAction; + QAction *aboutAction; + + QMenu *fileMenu; + QMenu *itemMenu; + QMenu *aboutMenu; + + QToolBar *textToolBar; + QToolBar *editToolBar; + QToolBar *colorToolBar; + QToolBar *pointerToolbar; + + QComboBox *sceneScaleCombo; + QComboBox *itemColorCombo; + QComboBox *textColorCombo; + QComboBox *fontSizeCombo; + QFontComboBox *fontCombo; + + QToolBox *toolBox; + QButtonGroup *buttonGroup; + QButtonGroup *pointerTypeGroup; + QButtonGroup *backgroundButtonGroup; + QToolButton *fontColorToolButton; + QToolButton *fillColorToolButton; + QToolButton *lineColorToolButton; + QAction *boldAction; + QAction *underlineAction; + QAction *italicAction; + QAction *textAction; + QAction *fillAction; + QAction *lineAction; +}; +//! [0] + +#endif diff --git a/examples/widgets/graphicsview/dragdroprobot/coloritem.cpp b/examples/widgets/graphicsview/dragdroprobot/coloritem.cpp new file mode 100644 index 0000000000..18e7a01af2 --- /dev/null +++ b/examples/widgets/graphicsview/dragdroprobot/coloritem.cpp @@ -0,0 +1,142 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> + +#include "coloritem.h" + +//! [0] +ColorItem::ColorItem() + : color(qrand() % 256, qrand() % 256, qrand() % 256) +{ + setToolTip(QString("QColor(%1, %2, %3)\n%4") + .arg(color.red()).arg(color.green()).arg(color.blue()) + .arg("Click and drag this color onto the robot!")); + setCursor(Qt::OpenHandCursor); + setAcceptedMouseButtons(Qt::LeftButton); +} +//! [0] + +//! [1] +QRectF ColorItem::boundingRect() const +{ + return QRectF(-15.5, -15.5, 34, 34); +} +//! [1] + +//! [2] +void ColorItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + Q_UNUSED(option); + Q_UNUSED(widget); + painter->setPen(Qt::NoPen); + painter->setBrush(Qt::darkGray); + painter->drawEllipse(-12, -12, 30, 30); + painter->setPen(QPen(Qt::black, 1)); + painter->setBrush(QBrush(color)); + painter->drawEllipse(-15, -15, 30, 30); +} +//! [2] + +//! [3] +void ColorItem::mousePressEvent(QGraphicsSceneMouseEvent *) +{ + setCursor(Qt::ClosedHandCursor); +} +//! [3] + +//! [5] +void ColorItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +{ + if (QLineF(event->screenPos(), event->buttonDownScreenPos(Qt::LeftButton)) + .length() < QApplication::startDragDistance()) { + return; + } + + QDrag *drag = new QDrag(event->widget()); + QMimeData *mime = new QMimeData; + drag->setMimeData(mime); +//! [5] + +//! [6] + static int n = 0; + if (n++ > 2 && (qrand() % 3) == 0) { + QImage image(":/images/head.png"); + mime->setImageData(image); + + drag->setPixmap(QPixmap::fromImage(image).scaled(30, 40)); + drag->setHotSpot(QPoint(15, 30)); +//! [6] +//! [7] + } else { + mime->setColorData(color); + mime->setText(QString("#%1%2%3") + .arg(color.red(), 2, 16, QLatin1Char('0')) + .arg(color.green(), 2, 16, QLatin1Char('0')) + .arg(color.blue(), 2, 16, QLatin1Char('0'))); + + QPixmap pixmap(34, 34); + pixmap.fill(Qt::white); + + QPainter painter(&pixmap); + painter.translate(15, 15); + painter.setRenderHint(QPainter::Antialiasing); + paint(&painter, 0, 0); + painter.end(); + + pixmap.setMask(pixmap.createHeuristicMask()); + + drag->setPixmap(pixmap); + drag->setHotSpot(QPoint(15, 20)); + } +//! [7] + +//! [8] + drag->exec(); + setCursor(Qt::OpenHandCursor); +} +//! [8] + +//! [4] +void ColorItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *) +{ + setCursor(Qt::OpenHandCursor); +} +//! [4] diff --git a/examples/widgets/graphicsview/dragdroprobot/coloritem.h b/examples/widgets/graphicsview/dragdroprobot/coloritem.h new file mode 100644 index 0000000000..9d3b4a9693 --- /dev/null +++ b/examples/widgets/graphicsview/dragdroprobot/coloritem.h @@ -0,0 +1,65 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef COLORITEM_H +#define COLORITEM_H + +#include <QGraphicsItem> + +//! [0] +class ColorItem : public QGraphicsItem +{ +public: + ColorItem(); + + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + +protected: + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseMoveEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + +private: + QColor color; +}; +//! [0] + +#endif diff --git a/examples/widgets/graphicsview/dragdroprobot/dragdroprobot.desktop b/examples/widgets/graphicsview/dragdroprobot/dragdroprobot.desktop new file mode 100644 index 0000000000..c01e3a3425 --- /dev/null +++ b/examples/widgets/graphicsview/dragdroprobot/dragdroprobot.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Drag and Drop Robot +Exec=/opt/usr/bin/dragdroprobot +Icon=dragdroprobot +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/graphicsview/dragdroprobot/dragdroprobot.pro b/examples/widgets/graphicsview/dragdroprobot/dragdroprobot.pro new file mode 100644 index 0000000000..3e33bad2f9 --- /dev/null +++ b/examples/widgets/graphicsview/dragdroprobot/dragdroprobot.pro @@ -0,0 +1,22 @@ +HEADERS += \ + coloritem.h \ + robot.h + +SOURCES += \ + coloritem.cpp \ + main.cpp \ + robot.cpp + +RESOURCES += \ + robot.qrc + + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/dragdroprobot +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS dragdroprobot.pro images +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/dragdroprobot +INSTALLS += target sources + +QT += widgets + +simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/graphicsview/dragdroprobot/images/head.png b/examples/widgets/graphicsview/dragdroprobot/images/head.png Binary files differnew file mode 100644 index 0000000000..1e520e09b8 --- /dev/null +++ b/examples/widgets/graphicsview/dragdroprobot/images/head.png diff --git a/examples/widgets/graphicsview/dragdroprobot/main.cpp b/examples/widgets/graphicsview/dragdroprobot/main.cpp new file mode 100644 index 0000000000..05d3c8f1b3 --- /dev/null +++ b/examples/widgets/graphicsview/dragdroprobot/main.cpp @@ -0,0 +1,94 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> + +#include "coloritem.h" +#include "robot.h" + +#include <math.h> + +class GraphicsView : public QGraphicsView +{ +public: + GraphicsView(QGraphicsScene *scene) : QGraphicsView(scene) + { + } + +protected: + virtual void resizeEvent(QResizeEvent *) + { + } +}; + +//! [0] +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); +//! [0] +//! [1] + QGraphicsScene scene(-200, -200, 400, 400); + + for (int i = 0; i < 10; ++i) { + ColorItem *item = new ColorItem; + item->setPos(::sin((i * 6.28) / 10.0) * 150, + ::cos((i * 6.28) / 10.0) * 150); + + scene.addItem(item); + } + + Robot *robot = new Robot; + robot->setTransform(QTransform::fromScale(1.2, 1.2), true); + robot->setPos(0, -20); + scene.addItem(robot); +//! [1] +//! [2] + GraphicsView view(&scene); + view.setRenderHint(QPainter::Antialiasing); + view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); + view.setBackgroundBrush(QColor(230, 200, 167)); + view.setWindowTitle("Drag and Drop Robot"); + view.show(); + + return app.exec(); +} +//! [2] diff --git a/examples/widgets/graphicsview/dragdroprobot/robot.cpp b/examples/widgets/graphicsview/dragdroprobot/robot.cpp new file mode 100644 index 0000000000..20935bf6c5 --- /dev/null +++ b/examples/widgets/graphicsview/dragdroprobot/robot.cpp @@ -0,0 +1,307 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> + +#include "robot.h" + +//! [0] +RobotPart::RobotPart(QGraphicsItem *parent) + : QGraphicsObject(parent), color(Qt::lightGray), dragOver(false) +{ + setAcceptDrops(true); +} +//! [0] + +//! [1] +void RobotPart::dragEnterEvent(QGraphicsSceneDragDropEvent *event) +{ + if (event->mimeData()->hasColor()) { + event->setAccepted(true); + dragOver = true; + update(); + } else { + event->setAccepted(false); + } +} +//! [1] + +//! [2] +void RobotPart::dragLeaveEvent(QGraphicsSceneDragDropEvent *event) +{ + Q_UNUSED(event); + dragOver = false; + update(); +} +//! [2] + +//! [3] +void RobotPart::dropEvent(QGraphicsSceneDragDropEvent *event) +{ + dragOver = false; + if (event->mimeData()->hasColor()) + color = qvariant_cast<QColor>(event->mimeData()->colorData()); + update(); +} +//! [3] + +//! [4] +RobotHead::RobotHead(QGraphicsItem *parent) + : RobotPart(parent) +{ +} +//! [4] + +//! [5] +QRectF RobotHead::boundingRect() const +{ + return QRectF(-15, -50, 30, 50); +} +//! [5] + +//! [6] +void RobotHead::paint(QPainter *painter, + const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + Q_UNUSED(option); + Q_UNUSED(widget); + if (pixmap.isNull()) { + painter->setBrush(dragOver ? color.light(130) : color); + painter->drawRoundedRect(-10, -30, 20, 30, 25, 25, Qt::RelativeSize); + painter->setBrush(Qt::white); + painter->drawEllipse(-7, -3 - 20, 7, 7); + painter->drawEllipse(0, -3 - 20, 7, 7); + painter->setBrush(Qt::black); + painter->drawEllipse(-5, -1 - 20, 2, 2); + painter->drawEllipse(2, -1 - 20, 2, 2); + painter->setPen(QPen(Qt::black, 2)); + painter->setBrush(Qt::NoBrush); + painter->drawArc(-6, -2 - 20, 12, 15, 190 * 16, 160 * 16); + } else { + painter->scale(.2272, .2824); + painter->drawPixmap(QPointF(-15 * 4.4, -50 * 3.54), pixmap); + } +} +//! [6] + +//! [7] +void RobotHead::dragEnterEvent(QGraphicsSceneDragDropEvent *event) +{ + if (event->mimeData()->hasImage()) { + event->setAccepted(true); + dragOver = true; + update(); + } else { + RobotPart::dragEnterEvent(event); + } +} +//! [7] + +//! [8] +void RobotHead::dropEvent(QGraphicsSceneDragDropEvent *event) +{ + if (event->mimeData()->hasImage()) { + dragOver = false; + pixmap = qvariant_cast<QPixmap>(event->mimeData()->imageData()); + update(); + } else { + RobotPart::dropEvent(event); + } +} +//! [8] + +RobotTorso::RobotTorso(QGraphicsItem *parent) + : RobotPart(parent) +{ +} + +QRectF RobotTorso::boundingRect() const +{ + return QRectF(-30, -20, 60, 60); +} + +void RobotTorso::paint(QPainter *painter, + const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + Q_UNUSED(option); + Q_UNUSED(widget); + + painter->setBrush(dragOver ? color.light(130) : color); + painter->drawRoundedRect(-20, -20, 40, 60, 25, 25, Qt::RelativeSize); + painter->drawEllipse(-25, -20, 20, 20); + painter->drawEllipse(5, -20, 20, 20); + painter->drawEllipse(-20, 22, 20, 20); + painter->drawEllipse(0, 22, 20, 20); +} + +RobotLimb::RobotLimb(QGraphicsItem *parent) + : RobotPart(parent) +{ +} + +QRectF RobotLimb::boundingRect() const +{ + return QRectF(-5, -5, 40, 10); +} + +void RobotLimb::paint(QPainter *painter, + const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + Q_UNUSED(option); + Q_UNUSED(widget); + + painter->setBrush(dragOver ? color.light(130) : color); + painter->drawRoundedRect(boundingRect(), 50, 50, Qt::RelativeSize); + painter->drawEllipse(-5, -5, 10, 10); +} + +//! [10] +Robot::Robot(QGraphicsItem *parent) + : RobotPart(parent) +{ + setFlag(ItemHasNoContents); + + QGraphicsObject *torsoItem = new RobotTorso(this); + QGraphicsObject *headItem = new RobotHead(torsoItem); + QGraphicsObject *upperLeftArmItem = new RobotLimb(torsoItem); + QGraphicsObject *lowerLeftArmItem = new RobotLimb(upperLeftArmItem); + QGraphicsObject *upperRightArmItem = new RobotLimb(torsoItem); + QGraphicsObject *lowerRightArmItem = new RobotLimb(upperRightArmItem); + QGraphicsObject *upperRightLegItem = new RobotLimb(torsoItem); + QGraphicsObject *lowerRightLegItem = new RobotLimb(upperRightLegItem); + QGraphicsObject *upperLeftLegItem = new RobotLimb(torsoItem); + QGraphicsObject *lowerLeftLegItem = new RobotLimb(upperLeftLegItem); +//! [10] + +//! [11] + headItem->setPos(0, -18); + upperLeftArmItem->setPos(-15, -10); + lowerLeftArmItem->setPos(30, 0); + upperRightArmItem->setPos(15, -10); + lowerRightArmItem->setPos(30, 0); + upperRightLegItem->setPos(10, 32); + lowerRightLegItem->setPos(30, 0); + upperLeftLegItem->setPos(-10, 32); + lowerLeftLegItem->setPos(30, 0); +//! [11] + +//! [12] + QParallelAnimationGroup *animation = new QParallelAnimationGroup(this); + + QPropertyAnimation *headAnimation = new QPropertyAnimation(headItem, "rotation"); + headAnimation->setStartValue(20); + headAnimation->setEndValue(-20); + QPropertyAnimation *headScaleAnimation = new QPropertyAnimation(headItem, "scale"); + headScaleAnimation->setEndValue(1.1); + animation->addAnimation(headAnimation); + animation->addAnimation(headScaleAnimation); +//! [12] + + QPropertyAnimation *upperLeftArmAnimation = new QPropertyAnimation(upperLeftArmItem, "rotation"); + upperLeftArmAnimation->setStartValue(190); + upperLeftArmAnimation->setEndValue(180); + animation->addAnimation(upperLeftArmAnimation); + + QPropertyAnimation *lowerLeftArmAnimation = new QPropertyAnimation(lowerLeftArmItem, "rotation"); + lowerLeftArmAnimation->setStartValue(50); + lowerLeftArmAnimation->setEndValue(10); + animation->addAnimation(lowerLeftArmAnimation); + + QPropertyAnimation *upperRightArmAnimation = new QPropertyAnimation(upperRightArmItem, "rotation"); + upperRightArmAnimation->setStartValue(300); + upperRightArmAnimation->setEndValue(310); + animation->addAnimation(upperRightArmAnimation); + + QPropertyAnimation *lowerRightArmAnimation = new QPropertyAnimation(lowerRightArmItem, "rotation"); + lowerRightArmAnimation->setStartValue(0); + lowerRightArmAnimation->setEndValue(-70); + animation->addAnimation(lowerRightArmAnimation); + + QPropertyAnimation *upperLeftLegAnimation = new QPropertyAnimation(upperLeftLegItem, "rotation"); + upperLeftLegAnimation->setStartValue(150); + upperLeftLegAnimation->setEndValue(80); + animation->addAnimation(upperLeftLegAnimation); + + QPropertyAnimation *lowerLeftLegAnimation = new QPropertyAnimation(lowerLeftLegItem, "rotation"); + lowerLeftLegAnimation->setStartValue(70); + lowerLeftLegAnimation->setEndValue(10); + animation->addAnimation(lowerLeftLegAnimation); + + QPropertyAnimation *upperRightLegAnimation = new QPropertyAnimation(upperRightLegItem, "rotation"); + upperRightLegAnimation->setStartValue(40); + upperRightLegAnimation->setEndValue(120); + animation->addAnimation(upperRightLegAnimation); + + QPropertyAnimation *lowerRightLegAnimation = new QPropertyAnimation(lowerRightLegItem, "rotation"); + lowerRightLegAnimation->setStartValue(10); + lowerRightLegAnimation->setEndValue(50); + animation->addAnimation(lowerRightLegAnimation); + + QPropertyAnimation *torsoAnimation = new QPropertyAnimation(torsoItem, "rotation"); + torsoAnimation->setStartValue(5); + torsoAnimation->setEndValue(-20); + animation->addAnimation(torsoAnimation); + +//! [13] + for (int i = 0; i < animation->animationCount(); ++i) { + QPropertyAnimation *anim = qobject_cast<QPropertyAnimation *>(animation->animationAt(i)); + anim->setEasingCurve(QEasingCurve::SineCurve); + anim->setDuration(2000); + } + + animation->setLoopCount(-1); + animation->start(); +//! [13] +} + +//! [9] +QRectF Robot::boundingRect() const +{ + return QRectF(); +} + +void Robot::paint(QPainter *painter, + const QStyleOptionGraphicsItem *option, QWidget *widget) +{ + Q_UNUSED(painter); + Q_UNUSED(option); + Q_UNUSED(widget); +} +//! [9] diff --git a/examples/widgets/graphicsview/dragdroprobot/robot.h b/examples/widgets/graphicsview/dragdroprobot/robot.h new file mode 100644 index 0000000000..ff9fb49485 --- /dev/null +++ b/examples/widgets/graphicsview/dragdroprobot/robot.h @@ -0,0 +1,118 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ROBOT_H +#define ROBOT_H + +#include <QGraphicsItem> + +QT_BEGIN_NAMESPACE +class QGraphicsSceneMouseEvent; +class QParallelAnimationGroup; +QT_END_NAMESPACE + +//! [0] +class RobotPart : public QGraphicsObject +{ +public: + RobotPart(QGraphicsItem *parent = 0); + +protected: + void dragEnterEvent(QGraphicsSceneDragDropEvent *event); + void dragLeaveEvent(QGraphicsSceneDragDropEvent *event); + void dropEvent(QGraphicsSceneDragDropEvent *event); + + QColor color; + bool dragOver; +}; +//! [0] + +//! [1] +class RobotHead : public RobotPart +{ +public: + RobotHead(QGraphicsItem *parent = 0); + + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); + +protected: + void dragEnterEvent(QGraphicsSceneDragDropEvent *event); + void dropEvent(QGraphicsSceneDragDropEvent *event); + +private: + QPixmap pixmap; +}; +//! [1] + +//! [2] +class RobotTorso : public RobotPart +{ +public: + RobotTorso(QGraphicsItem *parent = 0); + + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); +}; +//! [2] + +//! [3] +class RobotLimb : public RobotPart +{ +public: + RobotLimb(QGraphicsItem *parent = 0); + + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); +}; +//! [3] + +//! [4] +class Robot : public RobotPart +{ +public: + Robot(QGraphicsItem *parent = 0); + + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); +}; +//! [4] + +#endif diff --git a/examples/widgets/graphicsview/dragdroprobot/robot.qrc b/examples/widgets/graphicsview/dragdroprobot/robot.qrc new file mode 100644 index 0000000000..b0969d2a64 --- /dev/null +++ b/examples/widgets/graphicsview/dragdroprobot/robot.qrc @@ -0,0 +1,5 @@ +<RCC> + <qresource prefix="/" > + <file>images/head.png</file> + </qresource> +</RCC> diff --git a/examples/widgets/graphicsview/elasticnodes/edge.cpp b/examples/widgets/graphicsview/elasticnodes/edge.cpp new file mode 100644 index 0000000000..ee7334cdcc --- /dev/null +++ b/examples/widgets/graphicsview/elasticnodes/edge.cpp @@ -0,0 +1,149 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QPainter> + +#include "edge.h" +#include "node.h" + +#include <math.h> + +static const double Pi = 3.14159265358979323846264338327950288419717; +static double TwoPi = 2.0 * Pi; + +//! [0] +Edge::Edge(Node *sourceNode, Node *destNode) + : arrowSize(10) +{ + setAcceptedMouseButtons(0); + source = sourceNode; + dest = destNode; + source->addEdge(this); + dest->addEdge(this); + adjust(); +} +//! [0] + +//! [1] +Node *Edge::sourceNode() const +{ + return source; +} + +Node *Edge::destNode() const +{ + return dest; +} +//! [1] + +//! [2] +void Edge::adjust() +{ + if (!source || !dest) + return; + + QLineF line(mapFromItem(source, 0, 0), mapFromItem(dest, 0, 0)); + qreal length = line.length(); + + prepareGeometryChange(); + + if (length > qreal(20.)) { + QPointF edgeOffset((line.dx() * 10) / length, (line.dy() * 10) / length); + sourcePoint = line.p1() + edgeOffset; + destPoint = line.p2() - edgeOffset; + } else { + sourcePoint = destPoint = line.p1(); + } +} +//! [2] + +//! [3] +QRectF Edge::boundingRect() const +{ + if (!source || !dest) + return QRectF(); + + qreal penWidth = 1; + qreal extra = (penWidth + arrowSize) / 2.0; + + return QRectF(sourcePoint, QSizeF(destPoint.x() - sourcePoint.x(), + destPoint.y() - sourcePoint.y())) + .normalized() + .adjusted(-extra, -extra, extra, extra); +} +//! [3] + +//! [4] +void Edge::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +{ + if (!source || !dest) + return; + + QLineF line(sourcePoint, destPoint); + if (qFuzzyCompare(line.length(), qreal(0.))) + return; +//! [4] + +//! [5] + // Draw the line itself + painter->setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + painter->drawLine(line); +//! [5] + +//! [6] + // Draw the arrows + double angle = ::acos(line.dx() / line.length()); + if (line.dy() >= 0) + angle = TwoPi - angle; + + QPointF sourceArrowP1 = sourcePoint + QPointF(sin(angle + Pi / 3) * arrowSize, + cos(angle + Pi / 3) * arrowSize); + QPointF sourceArrowP2 = sourcePoint + QPointF(sin(angle + Pi - Pi / 3) * arrowSize, + cos(angle + Pi - Pi / 3) * arrowSize); + QPointF destArrowP1 = destPoint + QPointF(sin(angle - Pi / 3) * arrowSize, + cos(angle - Pi / 3) * arrowSize); + QPointF destArrowP2 = destPoint + QPointF(sin(angle - Pi + Pi / 3) * arrowSize, + cos(angle - Pi + Pi / 3) * arrowSize); + + painter->setBrush(Qt::black); + painter->drawPolygon(QPolygonF() << line.p1() << sourceArrowP1 << sourceArrowP2); + painter->drawPolygon(QPolygonF() << line.p2() << destArrowP1 << destArrowP2); +} +//! [6] diff --git a/examples/widgets/graphicsview/elasticnodes/edge.h b/examples/widgets/graphicsview/elasticnodes/edge.h new file mode 100644 index 0000000000..9bf4112212 --- /dev/null +++ b/examples/widgets/graphicsview/elasticnodes/edge.h @@ -0,0 +1,75 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef EDGE_H +#define EDGE_H + +#include <QGraphicsItem> + +class Node; + +//! [0] +class Edge : public QGraphicsItem +{ +public: + Edge(Node *sourceNode, Node *destNode); + + Node *sourceNode() const; + Node *destNode() const; + + void adjust(); + + enum { Type = UserType + 2 }; + int type() const { return Type; } + +protected: + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + +private: + Node *source, *dest; + + QPointF sourcePoint; + QPointF destPoint; + qreal arrowSize; +}; +//! [0] + +#endif diff --git a/examples/widgets/graphicsview/elasticnodes/elasticnodes.desktop b/examples/widgets/graphicsview/elasticnodes/elasticnodes.desktop new file mode 100644 index 0000000000..64402d080f --- /dev/null +++ b/examples/widgets/graphicsview/elasticnodes/elasticnodes.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Elastic Nodes +Exec=/opt/usr/bin/elasticnodes +Icon=elasticnodes +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/graphicsview/elasticnodes/elasticnodes.pro b/examples/widgets/graphicsview/elasticnodes/elasticnodes.pro new file mode 100644 index 0000000000..2a61809457 --- /dev/null +++ b/examples/widgets/graphicsview/elasticnodes/elasticnodes.pro @@ -0,0 +1,20 @@ +HEADERS += \ + edge.h \ + node.h \ + graphwidget.h + +SOURCES += \ + edge.cpp \ + main.cpp \ + node.cpp \ + graphwidget.cpp + +TARGET.EPOCHEAPSIZE = 0x200000 0xA00000 + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/elasticnodes +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS elasticnodes.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/elasticnodes +INSTALLS += target sources + +QT += widgets diff --git a/examples/widgets/graphicsview/elasticnodes/graphwidget.cpp b/examples/widgets/graphicsview/elasticnodes/graphwidget.cpp new file mode 100644 index 0000000000..36005b85f4 --- /dev/null +++ b/examples/widgets/graphicsview/elasticnodes/graphwidget.cpp @@ -0,0 +1,250 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "graphwidget.h" +#include "edge.h" +#include "node.h" + +#include <QtWidgets> + +#include <math.h> + +//! [0] +GraphWidget::GraphWidget(QWidget *parent) + : QGraphicsView(parent), timerId(0) +{ + QGraphicsScene *scene = new QGraphicsScene(this); + scene->setItemIndexMethod(QGraphicsScene::NoIndex); + scene->setSceneRect(-200, -200, 400, 400); + setScene(scene); + setCacheMode(CacheBackground); + setViewportUpdateMode(BoundingRectViewportUpdate); + setRenderHint(QPainter::Antialiasing); + setTransformationAnchor(AnchorUnderMouse); + scale(qreal(0.8), qreal(0.8)); + setMinimumSize(400, 400); + setWindowTitle(tr("Elastic Nodes")); +//! [0] + +//! [1] + Node *node1 = new Node(this); + Node *node2 = new Node(this); + Node *node3 = new Node(this); + Node *node4 = new Node(this); + centerNode = new Node(this); + Node *node6 = new Node(this); + Node *node7 = new Node(this); + Node *node8 = new Node(this); + Node *node9 = new Node(this); + scene->addItem(node1); + scene->addItem(node2); + scene->addItem(node3); + scene->addItem(node4); + scene->addItem(centerNode); + scene->addItem(node6); + scene->addItem(node7); + scene->addItem(node8); + scene->addItem(node9); + scene->addItem(new Edge(node1, node2)); + scene->addItem(new Edge(node2, node3)); + scene->addItem(new Edge(node2, centerNode)); + scene->addItem(new Edge(node3, node6)); + scene->addItem(new Edge(node4, node1)); + scene->addItem(new Edge(node4, centerNode)); + scene->addItem(new Edge(centerNode, node6)); + scene->addItem(new Edge(centerNode, node8)); + scene->addItem(new Edge(node6, node9)); + scene->addItem(new Edge(node7, node4)); + scene->addItem(new Edge(node8, node7)); + scene->addItem(new Edge(node9, node8)); + + node1->setPos(-50, -50); + node2->setPos(0, -50); + node3->setPos(50, -50); + node4->setPos(-50, 0); + centerNode->setPos(0, 0); + node6->setPos(50, 0); + node7->setPos(-50, 50); + node8->setPos(0, 50); + node9->setPos(50, 50); +} +//! [1] + +//! [2] +void GraphWidget::itemMoved() +{ + if (!timerId) + timerId = startTimer(1000 / 25); +} +//! [2] + +//! [3] +void GraphWidget::keyPressEvent(QKeyEvent *event) +{ + switch (event->key()) { + case Qt::Key_Up: + centerNode->moveBy(0, -20); + break; + case Qt::Key_Down: + centerNode->moveBy(0, 20); + break; + case Qt::Key_Left: + centerNode->moveBy(-20, 0); + break; + case Qt::Key_Right: + centerNode->moveBy(20, 0); + break; + case Qt::Key_Plus: + zoomIn(); + break; + case Qt::Key_Minus: + zoomOut(); + break; + case Qt::Key_Space: + case Qt::Key_Enter: + shuffle(); + break; + default: + QGraphicsView::keyPressEvent(event); + } +} +//! [3] + +//! [4] +void GraphWidget::timerEvent(QTimerEvent *event) +{ + Q_UNUSED(event); + + QList<Node *> nodes; + foreach (QGraphicsItem *item, scene()->items()) { + if (Node *node = qgraphicsitem_cast<Node *>(item)) + nodes << node; + } + + foreach (Node *node, nodes) + node->calculateForces(); + + bool itemsMoved = false; + foreach (Node *node, nodes) { + if (node->advance()) + itemsMoved = true; + } + + if (!itemsMoved) { + killTimer(timerId); + timerId = 0; + } +} +//! [4] + +//! [5] +void GraphWidget::wheelEvent(QWheelEvent *event) +{ + scaleView(pow((double)2, -event->delta() / 240.0)); +} +//! [5] + +//! [6] +void GraphWidget::drawBackground(QPainter *painter, const QRectF &rect) +{ + Q_UNUSED(rect); + + // Shadow + QRectF sceneRect = this->sceneRect(); + QRectF rightShadow(sceneRect.right(), sceneRect.top() + 5, 5, sceneRect.height()); + QRectF bottomShadow(sceneRect.left() + 5, sceneRect.bottom(), sceneRect.width(), 5); + if (rightShadow.intersects(rect) || rightShadow.contains(rect)) + painter->fillRect(rightShadow, Qt::darkGray); + if (bottomShadow.intersects(rect) || bottomShadow.contains(rect)) + painter->fillRect(bottomShadow, Qt::darkGray); + + // Fill + QLinearGradient gradient(sceneRect.topLeft(), sceneRect.bottomRight()); + gradient.setColorAt(0, Qt::white); + gradient.setColorAt(1, Qt::lightGray); + painter->fillRect(rect.intersected(sceneRect), gradient); + painter->setBrush(Qt::NoBrush); + painter->drawRect(sceneRect); + + // Text + QRectF textRect(sceneRect.left() + 4, sceneRect.top() + 4, + sceneRect.width() - 4, sceneRect.height() - 4); + QString message(tr("Click and drag the nodes around, and zoom with the mouse " + "wheel or the '+' and '-' keys")); + + QFont font = painter->font(); + font.setBold(true); + font.setPointSize(14); + painter->setFont(font); + painter->setPen(Qt::lightGray); + painter->drawText(textRect.translated(2, 2), message); + painter->setPen(Qt::black); + painter->drawText(textRect, message); +} +//! [6] + +//! [7] +void GraphWidget::scaleView(qreal scaleFactor) +{ + qreal factor = transform().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width(); + if (factor < 0.07 || factor > 100) + return; + + scale(scaleFactor, scaleFactor); +} +//! [7] + +void GraphWidget::shuffle() +{ + foreach (QGraphicsItem *item, scene()->items()) { + if (qgraphicsitem_cast<Node *>(item)) + item->setPos(-150 + qrand() % 300, -150 + qrand() % 300); + } +} + +void GraphWidget::zoomIn() +{ + scaleView(qreal(1.2)); +} + +void GraphWidget::zoomOut() +{ + scaleView(1 / qreal(1.2)); +} diff --git a/examples/widgets/graphicsview/elasticnodes/graphwidget.h b/examples/widgets/graphicsview/elasticnodes/graphwidget.h new file mode 100644 index 0000000000..61bcfdb5cb --- /dev/null +++ b/examples/widgets/graphicsview/elasticnodes/graphwidget.h @@ -0,0 +1,77 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef GRAPHWIDGET_H +#define GRAPHWIDGET_H + +#include <QtWidgets/QGraphicsView> + +class Node; + +//! [0] +class GraphWidget : public QGraphicsView +{ + Q_OBJECT + +public: + GraphWidget(QWidget *parent = 0); + + void itemMoved(); + +public slots: + void shuffle(); + void zoomIn(); + void zoomOut(); + +protected: + void keyPressEvent(QKeyEvent *event); + void timerEvent(QTimerEvent *event); + void wheelEvent(QWheelEvent *event); + void drawBackground(QPainter *painter, const QRectF &rect); + + void scaleView(qreal scaleFactor); + +private: + int timerId; + Node *centerNode; +}; +//! [0] + +#endif diff --git a/examples/widgets/graphicsview/elasticnodes/main.cpp b/examples/widgets/graphicsview/elasticnodes/main.cpp new file mode 100644 index 0000000000..239b8290ea --- /dev/null +++ b/examples/widgets/graphicsview/elasticnodes/main.cpp @@ -0,0 +1,57 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> + +#include "graphwidget.h" + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); + + GraphWidget *widget = new GraphWidget; + + QMainWindow mainWindow; + mainWindow.setCentralWidget(widget); + + mainWindow.show(); + return app.exec(); +} diff --git a/examples/widgets/graphicsview/elasticnodes/node.cpp b/examples/widgets/graphicsview/elasticnodes/node.cpp new file mode 100644 index 0000000000..dad226a5e6 --- /dev/null +++ b/examples/widgets/graphicsview/elasticnodes/node.cpp @@ -0,0 +1,212 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QGraphicsScene> +#include <QGraphicsSceneMouseEvent> +#include <QPainter> +#include <QStyleOption> + +#include "edge.h" +#include "node.h" +#include "graphwidget.h" + +//! [0] +Node::Node(GraphWidget *graphWidget) + : graph(graphWidget) +{ + setFlag(ItemIsMovable); + setFlag(ItemSendsGeometryChanges); + setCacheMode(DeviceCoordinateCache); + setZValue(-1); +} +//! [0] + +//! [1] +void Node::addEdge(Edge *edge) +{ + edgeList << edge; + edge->adjust(); +} + +QList<Edge *> Node::edges() const +{ + return edgeList; +} +//! [1] + +//! [2] +void Node::calculateForces() +{ + if (!scene() || scene()->mouseGrabberItem() == this) { + newPos = pos(); + return; + } +//! [2] + +//! [3] + // Sum up all forces pushing this item away + qreal xvel = 0; + qreal yvel = 0; + foreach (QGraphicsItem *item, scene()->items()) { + Node *node = qgraphicsitem_cast<Node *>(item); + if (!node) + continue; + + QPointF vec = mapToItem(node, 0, 0); + qreal dx = vec.x(); + qreal dy = vec.y(); + double l = 2.0 * (dx * dx + dy * dy); + if (l > 0) { + xvel += (dx * 150.0) / l; + yvel += (dy * 150.0) / l; + } + } +//! [3] + +//! [4] + // Now subtract all forces pulling items together + double weight = (edgeList.size() + 1) * 10; + foreach (Edge *edge, edgeList) { + QPointF vec; + if (edge->sourceNode() == this) + vec = mapToItem(edge->destNode(), 0, 0); + else + vec = mapToItem(edge->sourceNode(), 0, 0); + xvel -= vec.x() / weight; + yvel -= vec.y() / weight; + } +//! [4] + +//! [5] + if (qAbs(xvel) < 0.1 && qAbs(yvel) < 0.1) + xvel = yvel = 0; +//! [5] + +//! [6] + QRectF sceneRect = scene()->sceneRect(); + newPos = pos() + QPointF(xvel, yvel); + newPos.setX(qMin(qMax(newPos.x(), sceneRect.left() + 10), sceneRect.right() - 10)); + newPos.setY(qMin(qMax(newPos.y(), sceneRect.top() + 10), sceneRect.bottom() - 10)); +} +//! [6] + +//! [7] +bool Node::advance() +{ + if (newPos == pos()) + return false; + + setPos(newPos); + return true; +} +//! [7] + +//! [8] +QRectF Node::boundingRect() const +{ + qreal adjust = 2; + return QRectF( -10 - adjust, -10 - adjust, + 23 + adjust, 23 + adjust); +} +//! [8] + +//! [9] +QPainterPath Node::shape() const +{ + QPainterPath path; + path.addEllipse(-10, -10, 20, 20); + return path; +} +//! [9] + +//! [10] +void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) +{ + painter->setPen(Qt::NoPen); + painter->setBrush(Qt::darkGray); + painter->drawEllipse(-7, -7, 20, 20); + + QRadialGradient gradient(-3, -3, 10); + if (option->state & QStyle::State_Sunken) { + gradient.setCenter(3, 3); + gradient.setFocalPoint(3, 3); + gradient.setColorAt(1, QColor(Qt::yellow).light(120)); + gradient.setColorAt(0, QColor(Qt::darkYellow).light(120)); + } else { + gradient.setColorAt(0, Qt::yellow); + gradient.setColorAt(1, Qt::darkYellow); + } + painter->setBrush(gradient); + + painter->setPen(QPen(Qt::black, 0)); + painter->drawEllipse(-10, -10, 20, 20); +} +//! [10] + +//! [11] +QVariant Node::itemChange(GraphicsItemChange change, const QVariant &value) +{ + switch (change) { + case ItemPositionHasChanged: + foreach (Edge *edge, edgeList) + edge->adjust(); + graph->itemMoved(); + break; + default: + break; + }; + + return QGraphicsItem::itemChange(change, value); +} +//! [11] + +//! [12] +void Node::mousePressEvent(QGraphicsSceneMouseEvent *event) +{ + update(); + QGraphicsItem::mousePressEvent(event); +} + +void Node::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +{ + update(); + QGraphicsItem::mouseReleaseEvent(event); +} +//! [12] diff --git a/examples/widgets/graphicsview/elasticnodes/node.h b/examples/widgets/graphicsview/elasticnodes/node.h new file mode 100644 index 0000000000..86ca407e08 --- /dev/null +++ b/examples/widgets/graphicsview/elasticnodes/node.h @@ -0,0 +1,85 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef NODE_H +#define NODE_H + +#include <QGraphicsItem> +#include <QList> + +class Edge; +class GraphWidget; +QT_BEGIN_NAMESPACE +class QGraphicsSceneMouseEvent; +QT_END_NAMESPACE + +//! [0] +class Node : public QGraphicsItem +{ +public: + Node(GraphWidget *graphWidget); + + void addEdge(Edge *edge); + QList<Edge *> edges() const; + + enum { Type = UserType + 1 }; + int type() const { return Type; } + + void calculateForces(); + bool advance(); + + QRectF boundingRect() const; + QPainterPath shape() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + +protected: + QVariant itemChange(GraphicsItemChange change, const QVariant &value); + + void mousePressEvent(QGraphicsSceneMouseEvent *event); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + +private: + QList<Edge *> edgeList; + QPointF newPos; + GraphWidget *graph; +}; +//! [0] + +#endif diff --git a/examples/widgets/graphicsview/embeddeddialogs/No-Ones-Laughing-3.jpg b/examples/widgets/graphicsview/embeddeddialogs/No-Ones-Laughing-3.jpg Binary files differnew file mode 100644 index 0000000000..445567fbda --- /dev/null +++ b/examples/widgets/graphicsview/embeddeddialogs/No-Ones-Laughing-3.jpg diff --git a/examples/widgets/graphicsview/embeddeddialogs/customproxy.cpp b/examples/widgets/graphicsview/embeddeddialogs/customproxy.cpp new file mode 100644 index 0000000000..2aa2986014 --- /dev/null +++ b/examples/widgets/graphicsview/embeddeddialogs/customproxy.cpp @@ -0,0 +1,167 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "customproxy.h" + +#include <QtWidgets> + +CustomProxy::CustomProxy(QGraphicsItem *parent, Qt::WindowFlags wFlags) + : QGraphicsProxyWidget(parent, wFlags), popupShown(false), currentPopup(0) +{ + timeLine = new QTimeLine(250, this); + connect(timeLine, SIGNAL(valueChanged(qreal)), + this, SLOT(updateStep(qreal))); + connect(timeLine, SIGNAL(stateChanged(QTimeLine::State)), + this, SLOT(stateChanged(QTimeLine::State))); +} + +QRectF CustomProxy::boundingRect() const +{ + return QGraphicsProxyWidget::boundingRect().adjusted(0, 0, 10, 10); +} + +void CustomProxy::paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option, + QWidget *widget) +{ + const QColor color(0, 0, 0, 64); + + QRectF r = windowFrameRect(); + QRectF right(r.right(), r.top() + 10, 10, r.height() - 10); + QRectF bottom(r.left() + 10, r.bottom(), r.width(), 10); + bool intersectsRight = right.intersects(option->exposedRect); + bool intersectsBottom = bottom.intersects(option->exposedRect); + if (intersectsRight && intersectsBottom) { + QPainterPath path; + path.addRect(right); + path.addRect(bottom); + painter->setPen(Qt::NoPen); + painter->setBrush(color); + painter->drawPath(path); + } else if (intersectsBottom) { + painter->fillRect(bottom, color); + } else if (intersectsRight) { + painter->fillRect(right, color); + } + + QGraphicsProxyWidget::paintWindowFrame(painter, option, widget); +} + +void CustomProxy::hoverEnterEvent(QGraphicsSceneHoverEvent *event) +{ + QGraphicsProxyWidget::hoverEnterEvent(event); + scene()->setActiveWindow(this); + if (timeLine->currentValue() != 1) + zoomIn(); +} + +void CustomProxy::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) +{ + QGraphicsProxyWidget::hoverLeaveEvent(event); + if (!popupShown && (timeLine->direction() != QTimeLine::Backward || timeLine->currentValue() != 0)) + zoomOut(); +} + +bool CustomProxy::sceneEventFilter(QGraphicsItem *watched, QEvent *event) +{ + if (watched->isWindow() && (event->type() == QEvent::UngrabMouse || event->type() == QEvent::GrabMouse)) { + popupShown = watched->isVisible(); + if (!popupShown && !isUnderMouse()) + zoomOut(); + } + return QGraphicsProxyWidget::sceneEventFilter(watched, event); +} + +QVariant CustomProxy::itemChange(GraphicsItemChange change, const QVariant &value) +{ + if (change == ItemChildAddedChange || change == ItemChildRemovedChange) { + if (change == ItemChildAddedChange) { + currentPopup = qvariant_cast<QGraphicsItem *>(value); + currentPopup->setCacheMode(ItemCoordinateCache); + if (scene()) + currentPopup->installSceneEventFilter(this); + } else if (scene()) { + currentPopup->removeSceneEventFilter(this); + currentPopup = 0; + } + } else if (currentPopup && change == ItemSceneHasChanged) { + currentPopup->installSceneEventFilter(this); + } + return QGraphicsProxyWidget::itemChange(change, value); +} + +void CustomProxy::updateStep(qreal step) +{ + QRectF r = boundingRect(); + setTransform(QTransform() + .translate(r.width() / 2, r.height() / 2) + .rotate(step * 30, Qt::XAxis) + .rotate(step * 10, Qt::YAxis) + .rotate(step * 5, Qt::ZAxis) + .scale(1 + 1.5 * step, 1 + 1.5 * step) + .translate(-r.width() / 2, -r.height() / 2)); +} + +void CustomProxy::stateChanged(QTimeLine::State state) +{ + if (state == QTimeLine::Running) { + if (timeLine->direction() == QTimeLine::Forward) + setCacheMode(ItemCoordinateCache); + } else if (state == QTimeLine::NotRunning) { + if (timeLine->direction() == QTimeLine::Backward) + setCacheMode(DeviceCoordinateCache); + } +} + +void CustomProxy::zoomIn() +{ + if (timeLine->direction() != QTimeLine::Forward) + timeLine->setDirection(QTimeLine::Forward); + if (timeLine->state() == QTimeLine::NotRunning) + timeLine->start(); +} + +void CustomProxy::zoomOut() +{ + if (timeLine->direction() != QTimeLine::Backward) + timeLine->setDirection(QTimeLine::Backward); + if (timeLine->state() == QTimeLine::NotRunning) + timeLine->start(); +} diff --git a/examples/widgets/graphicsview/embeddeddialogs/customproxy.h b/examples/widgets/graphicsview/embeddeddialogs/customproxy.h new file mode 100644 index 0000000000..c85bbaccd3 --- /dev/null +++ b/examples/widgets/graphicsview/embeddeddialogs/customproxy.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef CUSTOMPROXY_H +#define CUSTOMPROXY_H + +#include <QtCore/qtimeline.h> +#include <QtWidgets/qgraphicsproxywidget.h> + +class CustomProxy : public QGraphicsProxyWidget +{ + Q_OBJECT +public: + CustomProxy(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0); + + QRectF boundingRect() const; + void paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option, + QWidget *widget); + +protected: + void hoverEnterEvent(QGraphicsSceneHoverEvent *event); + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); + bool sceneEventFilter(QGraphicsItem *watched, QEvent *event); + QVariant itemChange(GraphicsItemChange change, const QVariant &value); + +private slots: + void updateStep(qreal step); + void stateChanged(QTimeLine::State); + void zoomIn(); + void zoomOut(); + +private: + QTimeLine *timeLine; + bool popupShown; + QGraphicsItem *currentPopup; +}; + +#endif diff --git a/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp new file mode 100644 index 0000000000..e306f32c71 --- /dev/null +++ b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp @@ -0,0 +1,106 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "embeddeddialog.h" +#include "ui_embeddeddialog.h" + +#include <QtWidgets> + +EmbeddedDialog::EmbeddedDialog(QWidget *parent) + : QDialog(parent) +{ + ui = new Ui_embeddedDialog; + ui->setupUi(this); + ui->layoutDirection->setCurrentIndex(layoutDirection() != Qt::LeftToRight); + + foreach (QString styleName, QStyleFactory::keys()) { + ui->style->addItem(styleName); + if (style()->objectName().toLower() == styleName.toLower()) + ui->style->setCurrentIndex(ui->style->count() - 1); + } + + connect(ui->layoutDirection, SIGNAL(activated(int)), + this, SLOT(layoutDirectionChanged(int))); + connect(ui->spacing, SIGNAL(valueChanged(int)), + this, SLOT(spacingChanged(int))); + connect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), + this, SLOT(fontChanged(QFont))); + connect(ui->style, SIGNAL(activated(QString)), + this, SLOT(styleChanged(QString))); +} + +EmbeddedDialog::~EmbeddedDialog() +{ + delete ui; +} + +void EmbeddedDialog::layoutDirectionChanged(int index) +{ + setLayoutDirection(index == 0 ? Qt::LeftToRight : Qt::RightToLeft); +} + +void EmbeddedDialog::spacingChanged(int spacing) +{ + layout()->setSpacing(spacing); + adjustSize(); +} + +void EmbeddedDialog::fontChanged(const QFont &font) +{ + setFont(font); +} + +static void setStyleHelper(QWidget *widget, QStyle *style) +{ + widget->setStyle(style); + widget->setPalette(style->standardPalette()); + foreach (QObject *child, widget->children()) { + if (QWidget *childWidget = qobject_cast<QWidget *>(child)) + setStyleHelper(childWidget, style); + } +} + +void EmbeddedDialog::styleChanged(const QString &styleName) +{ + QStyle *style = QStyleFactory::create(styleName); + if (style) + setStyleHelper(this, style); +} diff --git a/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.h b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.h new file mode 100644 index 0000000000..59aa4c244a --- /dev/null +++ b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.h @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef EMBEDDEDDIALOG_H +#define EMBEDDEDDIALOG_H + +#include <QtWidgets/qdialog.h> + +QT_FORWARD_DECLARE_CLASS(Ui_embeddedDialog); + +class EmbeddedDialog : public QDialog +{ + Q_OBJECT +public: + EmbeddedDialog(QWidget *parent = 0); + ~EmbeddedDialog(); + +private slots: + void layoutDirectionChanged(int index); + void spacingChanged(int spacing); + void fontChanged(const QFont &font); + void styleChanged(const QString &styleName); + +private: + Ui_embeddedDialog *ui; +}; + +#endif diff --git a/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.ui b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.ui new file mode 100644 index 0000000000..f967b10085 --- /dev/null +++ b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.ui @@ -0,0 +1,87 @@ +<ui version="4.0" > + <class>embeddedDialog</class> + <widget class="QDialog" name="embeddedDialog" > + <property name="geometry" > + <rect> + <x>0</x> + <y>0</y> + <width>407</width> + <height>134</height> + </rect> + </property> + <property name="windowTitle" > + <string>Embedded Dialog</string> + </property> + <layout class="QFormLayout" name="formLayout" > + <item row="0" column="0" > + <widget class="QLabel" name="label" > + <property name="text" > + <string>Layout Direction:</string> + </property> + <property name="buddy" > + <cstring>layoutDirection</cstring> + </property> + </widget> + </item> + <item row="0" column="1" > + <widget class="QComboBox" name="layoutDirection" > + <item> + <property name="text" > + <string>Left to Right</string> + </property> + </item> + <item> + <property name="text" > + <string>Right to Left</string> + </property> + </item> + </widget> + </item> + <item row="1" column="0" > + <widget class="QLabel" name="label_2" > + <property name="text" > + <string>Select Font:</string> + </property> + <property name="buddy" > + <cstring>fontComboBox</cstring> + </property> + </widget> + </item> + <item row="1" column="1" > + <widget class="QFontComboBox" name="fontComboBox" /> + </item> + <item row="2" column="0" > + <widget class="QLabel" name="label_3" > + <property name="text" > + <string>Style:</string> + </property> + <property name="buddy" > + <cstring>style</cstring> + </property> + </widget> + </item> + <item row="2" column="1" > + <widget class="QComboBox" name="style" /> + </item> + <item row="3" column="0" > + <widget class="QLabel" name="label_4" > + <property name="text" > + <string>Layout spacing:</string> + </property> + <property name="buddy" > + <cstring>spacing</cstring> + </property> + </widget> + </item> + <item row="3" column="1" > + <widget class="QSlider" name="spacing" > + <property name="orientation" > + <enum>Qt::Horizontal</enum> + </property> + </widget> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/examples/widgets/graphicsview/embeddeddialogs/embeddeddialogs.pro b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialogs.pro new file mode 100644 index 0000000000..6244df4b68 --- /dev/null +++ b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialogs.pro @@ -0,0 +1,19 @@ +SOURCES += main.cpp +SOURCES += customproxy.cpp embeddeddialog.cpp +HEADERS += customproxy.h embeddeddialog.h + +FORMS += embeddeddialog.ui +RESOURCES += embeddeddialogs.qrc + +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/embeddeddialogs +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.png *.jpg *.plist *.icns *.ico *.rc *.pro *.html *.doc images +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/embeddeddialogs +INSTALLS += target sources + +QT += widgets diff --git a/examples/widgets/graphicsview/embeddeddialogs/embeddeddialogs.qrc b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialogs.qrc new file mode 100644 index 0000000000..33be5038da --- /dev/null +++ b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialogs.qrc @@ -0,0 +1,5 @@ +<RCC> + <qresource> + <file>No-Ones-Laughing-3.jpg</file> + </qresource> +</RCC> diff --git a/examples/widgets/graphicsview/embeddeddialogs/main.cpp b/examples/widgets/graphicsview/embeddeddialogs/main.cpp new file mode 100644 index 0000000000..88b249e481 --- /dev/null +++ b/examples/widgets/graphicsview/embeddeddialogs/main.cpp @@ -0,0 +1,83 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "customproxy.h" +#include "embeddeddialog.h" + +#include <QtWidgets> + +int main(int argc, char *argv[]) +{ + Q_INIT_RESOURCE(embeddeddialogs); + QApplication app(argc, argv); + + QGraphicsScene scene; + scene.setStickyFocus(true); +#ifndef Q_OS_WINCE + const int gridSize = 10; +#else + const int gridSize = 5; +#endif + + for (int y = 0; y < gridSize; ++y) { + for (int x = 0; x < gridSize; ++x) { + CustomProxy *proxy = new CustomProxy(0, Qt::Window); + proxy->setWidget(new EmbeddedDialog); + + QRectF rect = proxy->boundingRect(); + + proxy->setPos(x * rect.width() * 1.05, y * rect.height() * 1.05); + proxy->setCacheMode(QGraphicsItem::DeviceCoordinateCache); + + scene.addItem(proxy); + } + } + scene.setSceneRect(scene.itemsBoundingRect()); + + QGraphicsView view(&scene); + view.scale(0.5, 0.5); + view.setRenderHints(view.renderHints() | QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + view.setBackgroundBrush(QPixmap(":/No-Ones-Laughing-3.jpg")); + view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); + view.show(); + view.setWindowTitle("Embedded Dialogs Example"); + return app.exec(); +} diff --git a/examples/widgets/graphicsview/flowlayout/flowlayout.cpp b/examples/widgets/graphicsview/flowlayout/flowlayout.cpp new file mode 100644 index 0000000000..3f787109eb --- /dev/null +++ b/examples/widgets/graphicsview/flowlayout/flowlayout.cpp @@ -0,0 +1,213 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "flowlayout.h" +#include <QtWidgets/qwidget.h> +#include <QtCore/qmath.h> + +FlowLayout::FlowLayout() +{ + m_spacing[0] = 6; + m_spacing[1] = 6; + QSizePolicy sp = sizePolicy(); + sp.setHeightForWidth(true); + setSizePolicy(sp); +} + +void FlowLayout::insertItem(int index, QGraphicsLayoutItem *item) +{ + item->setParentLayoutItem(this); + if (uint(index) > uint(m_items.count())) + index = m_items.count(); + m_items.insert(index, item); + invalidate(); +} + +int FlowLayout::count() const +{ + return m_items.count(); +} + +QGraphicsLayoutItem *FlowLayout::itemAt(int index) const +{ + return m_items.value(index); +} + +void FlowLayout::removeAt(int index) +{ + m_items.removeAt(index); + invalidate(); +} + +qreal FlowLayout::spacing(Qt::Orientation o) const +{ + return m_spacing[int(o) - 1]; +} + +void FlowLayout::setSpacing(Qt::Orientations o, qreal spacing) +{ + if (o & Qt::Horizontal) + m_spacing[0] = spacing; + if (o & Qt::Vertical) + m_spacing[1] = spacing; +} + +void FlowLayout::setGeometry(const QRectF &geom) +{ + QGraphicsLayout::setGeometry(geom); + doLayout(geom, true); +} + +qreal FlowLayout::doLayout(const QRectF &geom, bool applyNewGeometry) const +{ + qreal left, top, right, bottom; + getContentsMargins(&left, &top, &right, &bottom); + const qreal maxw = geom.width() - left - right; + + qreal x = 0; + qreal y = 0; + qreal maxRowHeight = 0; + QSizeF pref; + for (int i = 0; i < m_items.count(); ++i) { + QGraphicsLayoutItem *item = m_items.at(i); + pref = item->effectiveSizeHint(Qt::PreferredSize); + maxRowHeight = qMax(maxRowHeight, pref.height()); + + qreal next_x; + next_x = x + pref.width(); + if (next_x > maxw) { + if (x == 0) { + pref.setWidth(maxw); + } else { + x = 0; + next_x = pref.width(); + } + y += maxRowHeight + spacing(Qt::Vertical); + maxRowHeight = 0; + } + + if (applyNewGeometry) + item->setGeometry(QRectF(QPointF(left + x, top + y), pref)); + x = next_x + spacing(Qt::Horizontal); + } + maxRowHeight = qMax(maxRowHeight, pref.height()); + return top + y + maxRowHeight + bottom; +} + +QSizeF FlowLayout::minSize(const QSizeF &constraint) const +{ + QSizeF size(0, 0); + qreal left, top, right, bottom; + getContentsMargins(&left, &top, &right, &bottom); + if (constraint.width() >= 0) { // height for width + const qreal height = doLayout(QRectF(QPointF(0,0), constraint), false); + size = QSizeF(constraint.width(), height); + } else if (constraint.height() >= 0) { // width for height? + // not supported + } else { + QGraphicsLayoutItem *item; + foreach (item, m_items) + size = size.expandedTo(item->effectiveSizeHint(Qt::MinimumSize)); + size += QSize(left + right, top + bottom); + } + return size; +} + +QSizeF FlowLayout::prefSize() const +{ + qreal left, right; + getContentsMargins(&left, 0, &right, 0); + + QGraphicsLayoutItem *item; + qreal maxh = 0; + qreal totalWidth = 0; + foreach (item, m_items) { + if (totalWidth > 0) + totalWidth += spacing(Qt::Horizontal); + QSizeF pref = item->effectiveSizeHint(Qt::PreferredSize); + totalWidth += pref.width(); + maxh = qMax(maxh, pref.height()); + } + maxh += spacing(Qt::Vertical); + + const qreal goldenAspectRatio = 1.61803399; + qreal w = qSqrt(totalWidth * maxh * goldenAspectRatio) + left + right; + + return minSize(QSizeF(w, -1)); +} + +QSizeF FlowLayout::maxSize() const +{ + QGraphicsLayoutItem *item; + qreal totalWidth = 0; + qreal totalHeight = 0; + foreach (item, m_items) { + if (totalWidth > 0) + totalWidth += spacing(Qt::Horizontal); + if (totalHeight > 0) + totalHeight += spacing(Qt::Vertical); + QSizeF pref = item->effectiveSizeHint(Qt::PreferredSize); + totalWidth += pref.width(); + totalHeight += pref.height(); + } + + qreal left, top, right, bottom; + getContentsMargins(&left, &top, &right, &bottom); + return QSizeF(left + totalWidth + right, top + totalHeight + bottom); +} + +QSizeF FlowLayout::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const +{ + QSizeF sh = constraint; + switch (which) { + case Qt::PreferredSize: + sh = prefSize(); + break; + case Qt::MinimumSize: + sh = minSize(constraint); + break; + case Qt::MaximumSize: + sh = maxSize(); + break; + default: + break; + } + return sh; +} diff --git a/examples/widgets/graphicsview/flowlayout/flowlayout.desktop b/examples/widgets/graphicsview/flowlayout/flowlayout.desktop new file mode 100644 index 0000000000..54ea3b0290 --- /dev/null +++ b/examples/widgets/graphicsview/flowlayout/flowlayout.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Flow Layout +Exec=/opt/usr/bin/flowlayout +Icon=flowlayout +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/graphicsview/flowlayout/flowlayout.h b/examples/widgets/graphicsview/flowlayout/flowlayout.h new file mode 100644 index 0000000000..751e435ec0 --- /dev/null +++ b/examples/widgets/graphicsview/flowlayout/flowlayout.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets/qgraphicslayout.h> + +class FlowLayout : public QGraphicsLayout +{ +public: + FlowLayout(); + inline void addItem(QGraphicsLayoutItem *item); + void insertItem(int index, QGraphicsLayoutItem *item); + void setSpacing(Qt::Orientations o, qreal spacing); + qreal spacing(Qt::Orientation o) const; + + // inherited functions + void setGeometry(const QRectF &geom); + + int count() const; + QGraphicsLayoutItem *itemAt(int index) const; + void removeAt(int index); + +protected: + QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const; + +private: + qreal doLayout(const QRectF &geom, bool applyNewGeometry) const; + QSizeF minSize(const QSizeF &constraint) const; + QSizeF prefSize() const; + QSizeF maxSize() const; + + QList<QGraphicsLayoutItem*> m_items; + qreal m_spacing[2]; +}; + + +inline void FlowLayout::addItem(QGraphicsLayoutItem *item) +{ + insertItem(-1, item); +} diff --git a/examples/widgets/graphicsview/flowlayout/flowlayout.pro b/examples/widgets/graphicsview/flowlayout/flowlayout.pro new file mode 100644 index 0000000000..5f69a74d60 --- /dev/null +++ b/examples/widgets/graphicsview/flowlayout/flowlayout.pro @@ -0,0 +1,14 @@ +QT += widgets + +QMAKE_PROJECT_NAME = flowlayout_graphicsview + +HEADERS += flowlayout.h window.h +SOURCES += flowlayout.cpp main.cpp window.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/flowlayout +sources.files = $$SOURCES $$HEADERS *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/flowlayout +INSTALLS += target sources + +simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/graphicsview/flowlayout/main.cpp b/examples/widgets/graphicsview/flowlayout/main.cpp new file mode 100644 index 0000000000..a7a1155224 --- /dev/null +++ b/examples/widgets/graphicsview/flowlayout/main.cpp @@ -0,0 +1,57 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> +#include "window.h" + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + QGraphicsScene scene; + QGraphicsView *view = new QGraphicsView(&scene); + Window *w = new Window; + scene.addItem(w); + + view->resize(400, 300); + view->show(); + + return app.exec(); +} diff --git a/examples/widgets/graphicsview/flowlayout/window.cpp b/examples/widgets/graphicsview/flowlayout/window.cpp new file mode 100644 index 0000000000..193a2bbc6e --- /dev/null +++ b/examples/widgets/graphicsview/flowlayout/window.cpp @@ -0,0 +1,62 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets/qgraphicsproxywidget.h> +#include <QtWidgets/qlabel.h> +#include "flowlayout.h" +#include "window.h" + +Window::Window() +: QGraphicsWidget(0, Qt::Window) +{ + FlowLayout *lay = new FlowLayout; + QLatin1String wiseWords("I am not bothered by the fact that I am unknown." + " I am bothered when I do not know others. (Confucius)"); + QString sentence(wiseWords); + QStringList words = sentence.split(QLatin1Char(' '), QString::SkipEmptyParts); + for (int i = 0; i < words.count(); ++i) { + QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(this); + QLabel *label = new QLabel(words.at(i)); + label->setFrameStyle(QFrame::Box | QFrame::Plain); + proxy->setWidget(label); + lay->addItem(proxy); + } + setLayout(lay); +} diff --git a/examples/widgets/graphicsview/flowlayout/window.h b/examples/widgets/graphicsview/flowlayout/window.h new file mode 100644 index 0000000000..b1eb874c21 --- /dev/null +++ b/examples/widgets/graphicsview/flowlayout/window.h @@ -0,0 +1,47 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets/qgraphicswidget.h> + +class Window : public QGraphicsWidget { + Q_OBJECT +public: + Window(); +}; diff --git a/examples/widgets/graphicsview/graphicsview.pro b/examples/widgets/graphicsview/graphicsview.pro new file mode 100644 index 0000000000..6b7de527c6 --- /dev/null +++ b/examples/widgets/graphicsview/graphicsview.pro @@ -0,0 +1,28 @@ +TEMPLATE = subdirs +SUBDIRS = \ + chip \ + elasticnodes \ + embeddeddialogs \ + collidingmice \ + padnavigator \ + basicgraphicslayouts \ + diagramscene \ + dragdroprobot \ + flowlayout \ + anchorlayout \ + simpleanchorlayout \ + weatheranchorlayout + +contains(DEFINES, QT_NO_CURSOR)|contains(DEFINES, QT_NO_DRAGANDDROP): SUBDIRS -= dragdroprobot + +contains(QT_CONFIG, opengl):!contains(QT_CONFIG, opengles1):!contains(QT_CONFIG, opengles2):{ + SUBDIRS += boxes +} + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS graphicsview.pro README +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview +INSTALLS += target sources + +QT += widgets diff --git a/examples/widgets/graphicsview/padnavigator/flippablepad.cpp b/examples/widgets/graphicsview/padnavigator/flippablepad.cpp new file mode 100644 index 0000000000..a6c44af70c --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/flippablepad.cpp @@ -0,0 +1,98 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "flippablepad.h" + +#include <QtWidgets/QtWidgets> + +//! [0] +static QRectF boundsFromSize(const QSize &size) +{ + return QRectF((-size.width() / 2.0) * 150, (-size.height() / 2.0) * 150, + size.width() * 150, size.height() * 150); +} +//! [0] + +//! [1] +static QPointF posForLocation(int column, int row, const QSize &size) +{ + return QPointF(column * 150, row * 150) + - QPointF((size.width() - 1) * 75, (size.height() - 1) * 75); +} +//! [1] + +//! [2] +FlippablePad::FlippablePad(const QSize &size, QGraphicsItem *parent) + : RoundRectItem(boundsFromSize(size), QColor(226, 255, 92, 64), parent) +{ +//! [2] +//! [3] + int numIcons = size.width() * size.height(); + QList<QPixmap> pixmaps; + QDirIterator it(":/images", QStringList() << "*.png"); + while (it.hasNext() && pixmaps.size() < numIcons) + pixmaps << it.next(); +//! [3] + +//! [4] + const QRectF iconRect(-54, -54, 108, 108); + const QColor iconColor(214, 240, 110, 128); + iconGrid.resize(size.height()); + int n = 0; + + for (int y = 0; y < size.height(); ++y) { + iconGrid[y].resize(size.width()); + for (int x = 0; x < size.width(); ++x) { + RoundRectItem *rect = new RoundRectItem(iconRect, iconColor, this); + rect->setZValue(1); + rect->setPos(posForLocation(x, y, size)); + rect->setPixmap(pixmaps.at(n++ % pixmaps.size())); + iconGrid[y][x] = rect; + } + } +} +//! [4] + +//! [5] +RoundRectItem *FlippablePad::iconAt(int column, int row) const +{ + return iconGrid[row][column]; +} +//! [5] diff --git a/examples/widgets/graphicsview/padnavigator/flippablepad.h b/examples/widgets/graphicsview/padnavigator/flippablepad.h new file mode 100644 index 0000000000..e0d1fe24e5 --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/flippablepad.h @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef FLIPPABLEPAD_H +#define FLIPPABLEPAD_H + +#include "roundrectitem.h" + +#include <QGraphicsObject> +#include <QLinearGradient> +#include <QVector> + +//! [0] +class FlippablePad : public RoundRectItem +{ +public: + FlippablePad(const QSize &size, QGraphicsItem *parent = 0); + + RoundRectItem *iconAt(int column, int row) const; + +private: + QVector<QVector<RoundRectItem *> > iconGrid; +}; +//! [0] + +#endif // FLIPPABLEPAD_H diff --git a/examples/widgets/graphicsview/padnavigator/form.ui b/examples/widgets/graphicsview/padnavigator/form.ui new file mode 100644 index 0000000000..fc7d12321e --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/form.ui @@ -0,0 +1,208 @@ +<ui version="4.0" > + <class>Form</class> + <widget class="QWidget" name="Form" > + <property name="geometry" > + <rect> + <x>0</x> + <y>0</y> + <width>378</width> + <height>385</height> + </rect> + </property> + <property name="windowTitle" > + <string>BackSide</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout_2" > + <item> + <widget class="QGroupBox" name="groupBox" > + <property name="title" > + <string>Settings</string> + </property> + <property name="flat" > + <bool>true</bool> + </property> + <property name="checkable" > + <bool>true</bool> + </property> + <layout class="QGridLayout" name="gridLayout" > + <item row="0" column="0" > + <widget class="QLabel" name="label" > + <property name="text" > + <string>Title:</string> + </property> + </widget> + </item> + <item row="0" column="1" > + <widget class="QLineEdit" name="hostName" > + <property name="text" > + <string>Pad Navigator Example</string> + </property> + </widget> + </item> + <item row="1" column="0" > + <widget class="QLabel" name="label_2" > + <property name="text" > + <string>Modified:</string> + </property> + </widget> + </item> + <item row="2" column="0" > + <widget class="QLabel" name="label_3" > + <property name="text" > + <string>Extent</string> + </property> + </widget> + </item> + <item row="2" column="1" > + <layout class="QHBoxLayout" name="horizontalLayout" > + <item> + <widget class="QSlider" name="horizontalSlider" > + <property name="value" > + <number>42</number> + </property> + <property name="orientation" > + <enum>Qt::Horizontal</enum> + </property> + </widget> + </item> + <item> + <widget class="QSpinBox" name="spinBox" > + <property name="value" > + <number>42</number> + </property> + </widget> + </item> + </layout> + </item> + <item row="1" column="1" > + <widget class="QDateTimeEdit" name="dateTimeEdit" /> + </item> + </layout> + </widget> + </item> + <item> + <widget class="QGroupBox" name="groupBox_2" > + <property name="title" > + <string>Other input</string> + </property> + <property name="flat" > + <bool>true</bool> + </property> + <property name="checkable" > + <bool>true</bool> + </property> + <layout class="QHBoxLayout" name="horizontalLayout_2" > + <item> + <widget class="QTreeWidget" name="treeWidget" > + <column> + <property name="text" > + <string>Widgets On Graphics View</string> + </property> + </column> + <item> + <property name="text" > + <string>QGraphicsProxyWidget</string> + </property> + <item> + <property name="text" > + <string>QGraphicsWidget</string> + </property> + <item> + <property name="text" > + <string>QObject</string> + </property> + </item> + <item> + <property name="text" > + <string>QGraphicsItem</string> + </property> + </item> + <item> + <property name="text" > + <string>QGraphicsLayoutItem</string> + </property> + </item> + </item> + </item> + <item> + <property name="text" > + <string>QGraphicsGridLayout</string> + </property> + <item> + <property name="text" > + <string>QGraphicsLayout</string> + </property> + <item> + <property name="text" > + <string>QGraphicsLayoutItem</string> + </property> + </item> + </item> + </item> + <item> + <property name="text" > + <string>QGraphicsLinearLayout</string> + </property> + <item> + <property name="text" > + <string>QGraphicsLayout</string> + </property> + <item> + <property name="text" > + <string>QGraphicsLayoutItem</string> + </property> + </item> + </item> + </item> + </widget> + </item> + </layout> + </widget> + </item> + </layout> + </widget> + <tabstops> + <tabstop>groupBox</tabstop> + <tabstop>hostName</tabstop> + <tabstop>dateTimeEdit</tabstop> + <tabstop>horizontalSlider</tabstop> + <tabstop>spinBox</tabstop> + <tabstop>groupBox_2</tabstop> + <tabstop>treeWidget</tabstop> + </tabstops> + <resources/> + <connections> + <connection> + <sender>horizontalSlider</sender> + <signal>valueChanged(int)</signal> + <receiver>spinBox</receiver> + <slot>setValue(int)</slot> + <hints> + <hint type="sourcelabel" > + <x>184</x> + <y>125</y> + </hint> + <hint type="destinationlabel" > + <x>275</x> + <y>127</y> + </hint> + </hints> + </connection> + <connection> + <sender>spinBox</sender> + <signal>valueChanged(int)</signal> + <receiver>horizontalSlider</receiver> + <slot>setValue(int)</slot> + <hints> + <hint type="sourcelabel" > + <x>272</x> + <y>114</y> + </hint> + <hint type="destinationlabel" > + <x>190</x> + <y>126</y> + </hint> + </hints> + </connection> + </connections> +</ui> diff --git a/examples/widgets/graphicsview/padnavigator/images/artsfftscope.png b/examples/widgets/graphicsview/padnavigator/images/artsfftscope.png Binary files differnew file mode 100644 index 0000000000..4db003f8d2 --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/images/artsfftscope.png diff --git a/examples/widgets/graphicsview/padnavigator/images/blue_angle_swirl.jpg b/examples/widgets/graphicsview/padnavigator/images/blue_angle_swirl.jpg Binary files differnew file mode 100644 index 0000000000..5bf0debdbd --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/images/blue_angle_swirl.jpg diff --git a/examples/widgets/graphicsview/padnavigator/images/kontact_contacts.png b/examples/widgets/graphicsview/padnavigator/images/kontact_contacts.png Binary files differnew file mode 100644 index 0000000000..6fb4cc8f38 --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/images/kontact_contacts.png diff --git a/examples/widgets/graphicsview/padnavigator/images/kontact_journal.png b/examples/widgets/graphicsview/padnavigator/images/kontact_journal.png Binary files differnew file mode 100644 index 0000000000..b1fedb6982 --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/images/kontact_journal.png diff --git a/examples/widgets/graphicsview/padnavigator/images/kontact_mail.png b/examples/widgets/graphicsview/padnavigator/images/kontact_mail.png Binary files differnew file mode 100644 index 0000000000..672f8fa3ab --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/images/kontact_mail.png diff --git a/examples/widgets/graphicsview/padnavigator/images/kontact_notes.png b/examples/widgets/graphicsview/padnavigator/images/kontact_notes.png Binary files differnew file mode 100644 index 0000000000..229bf73ac6 --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/images/kontact_notes.png diff --git a/examples/widgets/graphicsview/padnavigator/images/kopeteavailable.png b/examples/widgets/graphicsview/padnavigator/images/kopeteavailable.png Binary files differnew file mode 100644 index 0000000000..2eaf41afec --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/images/kopeteavailable.png diff --git a/examples/widgets/graphicsview/padnavigator/images/metacontact_online.png b/examples/widgets/graphicsview/padnavigator/images/metacontact_online.png Binary files differnew file mode 100644 index 0000000000..6a398dd10f --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/images/metacontact_online.png diff --git a/examples/widgets/graphicsview/padnavigator/images/minitools.png b/examples/widgets/graphicsview/padnavigator/images/minitools.png Binary files differnew file mode 100644 index 0000000000..0248c9d50a --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/images/minitools.png diff --git a/examples/widgets/graphicsview/padnavigator/main.cpp b/examples/widgets/graphicsview/padnavigator/main.cpp new file mode 100644 index 0000000000..380fde8cd9 --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/main.cpp @@ -0,0 +1,55 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "padnavigator.h" + +#include <QtWidgets/QtWidgets> + +//! [0] +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + Q_INIT_RESOURCE(padnavigator); + + PadNavigator navigator(QSize(3, 3)); + navigator.show(); + return app.exec(); +} +//! [0] diff --git a/examples/widgets/graphicsview/padnavigator/padnavigator.cpp b/examples/widgets/graphicsview/padnavigator/padnavigator.cpp new file mode 100644 index 0000000000..fcfe84bb72 --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/padnavigator.cpp @@ -0,0 +1,306 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "flippablepad.h" +#include "padnavigator.h" +#include "splashitem.h" + +#include <QtWidgets/QtWidgets> +#ifndef QT_NO_OPENGL +#include <QtOpenGL/QtOpenGL> +#endif + +//! [0] +PadNavigator::PadNavigator(const QSize &size, QWidget *parent) + : QGraphicsView(parent) +{ +//! [0] +//! [1] + // Splash item + SplashItem *splash = new SplashItem; + splash->setZValue(1); +//! [1] + +//! [2] + // Pad item + FlippablePad *pad = new FlippablePad(size); + QGraphicsRotation *flipRotation = new QGraphicsRotation(pad); + QGraphicsRotation *xRotation = new QGraphicsRotation(pad); + QGraphicsRotation *yRotation = new QGraphicsRotation(pad); + flipRotation->setAxis(Qt::YAxis); + xRotation->setAxis(Qt::YAxis); + yRotation->setAxis(Qt::XAxis); + pad->setTransformations(QList<QGraphicsTransform *>() + << flipRotation + << xRotation << yRotation); +//! [2] + +//! [3] + // Back (proxy widget) item + QGraphicsProxyWidget *backItem = new QGraphicsProxyWidget(pad); + QWidget *widget = new QWidget; + form.setupUi(widget); + form.hostName->setFocus(); + backItem->setWidget(widget); + backItem->setVisible(false); + backItem->setFocus(); + backItem->setCacheMode(QGraphicsItem::ItemCoordinateCache); + const QRectF r = backItem->rect(); + backItem->setTransform(QTransform() + .rotate(180, Qt::YAxis) + .translate(-r.width()/2, -r.height()/2)); +//! [3] + +//! [4] + // Selection item + RoundRectItem *selectionItem = new RoundRectItem(QRectF(-60, -60, 120, 120), + Qt::gray, pad); + selectionItem->setZValue(0.5); +//! [4] + +//! [5] + // Splash animations + QPropertyAnimation *smoothSplashMove = new QPropertyAnimation(splash, "y"); + QPropertyAnimation *smoothSplashOpacity = new QPropertyAnimation(splash, "opacity"); + smoothSplashMove->setEasingCurve(QEasingCurve::InQuad); + smoothSplashMove->setDuration(250); + smoothSplashOpacity->setDuration(250); +//! [5] + +//! [6] + // Selection animation + QPropertyAnimation *smoothXSelection = new QPropertyAnimation(selectionItem, "x"); + QPropertyAnimation *smoothYSelection = new QPropertyAnimation(selectionItem, "y"); + QPropertyAnimation *smoothXRotation = new QPropertyAnimation(xRotation, "angle"); + QPropertyAnimation *smoothYRotation = new QPropertyAnimation(yRotation, "angle"); + smoothXSelection->setDuration(125); + smoothYSelection->setDuration(125); + smoothXRotation->setDuration(125); + smoothYRotation->setDuration(125); + smoothXSelection->setEasingCurve(QEasingCurve::InOutQuad); + smoothYSelection->setEasingCurve(QEasingCurve::InOutQuad); + smoothXRotation->setEasingCurve(QEasingCurve::InOutQuad); + smoothYRotation->setEasingCurve(QEasingCurve::InOutQuad); +//! [6] + +//! [7] + // Flip animation setup + QPropertyAnimation *smoothFlipRotation = new QPropertyAnimation(flipRotation, "angle"); + QPropertyAnimation *smoothFlipScale = new QPropertyAnimation(pad, "scale"); + QPropertyAnimation *smoothFlipXRotation = new QPropertyAnimation(xRotation, "angle"); + QPropertyAnimation *smoothFlipYRotation = new QPropertyAnimation(yRotation, "angle"); + QParallelAnimationGroup *flipAnimation = new QParallelAnimationGroup(this); + smoothFlipScale->setDuration(500); + smoothFlipRotation->setDuration(500); + smoothFlipXRotation->setDuration(500); + smoothFlipYRotation->setDuration(500); + smoothFlipScale->setEasingCurve(QEasingCurve::InOutQuad); + smoothFlipRotation->setEasingCurve(QEasingCurve::InOutQuad); + smoothFlipXRotation->setEasingCurve(QEasingCurve::InOutQuad); + smoothFlipYRotation->setEasingCurve(QEasingCurve::InOutQuad); + smoothFlipScale->setKeyValueAt(0, qvariant_cast<qreal>(1.0)); + smoothFlipScale->setKeyValueAt(0.5, qvariant_cast<qreal>(0.7)); + smoothFlipScale->setKeyValueAt(1, qvariant_cast<qreal>(1.0)); + flipAnimation->addAnimation(smoothFlipRotation); + flipAnimation->addAnimation(smoothFlipScale); + flipAnimation->addAnimation(smoothFlipXRotation); + flipAnimation->addAnimation(smoothFlipYRotation); +//! [7] + +//! [8] + // Flip animation delayed property assignment + QSequentialAnimationGroup *setVariablesSequence = new QSequentialAnimationGroup; + QPropertyAnimation *setFillAnimation = new QPropertyAnimation(pad, "fill"); + QPropertyAnimation *setBackItemVisibleAnimation = new QPropertyAnimation(backItem, "visible"); + QPropertyAnimation *setSelectionItemVisibleAnimation = new QPropertyAnimation(selectionItem, "visible"); + setFillAnimation->setDuration(0); + setBackItemVisibleAnimation->setDuration(0); + setSelectionItemVisibleAnimation->setDuration(0); + setVariablesSequence->addPause(250); + setVariablesSequence->addAnimation(setBackItemVisibleAnimation); + setVariablesSequence->addAnimation(setSelectionItemVisibleAnimation); + setVariablesSequence->addAnimation(setFillAnimation); + flipAnimation->addAnimation(setVariablesSequence); +//! [8] + +//! [9] + // Build the state machine + QStateMachine *stateMachine = new QStateMachine(this); + QState *splashState = new QState(stateMachine); + QState *frontState = new QState(stateMachine); + QHistoryState *historyState = new QHistoryState(frontState); + QState *backState = new QState(stateMachine); +//! [9] +//! [10] + frontState->assignProperty(pad, "fill", false); + frontState->assignProperty(splash, "opacity", 0.0); + frontState->assignProperty(backItem, "visible", false); + frontState->assignProperty(flipRotation, "angle", qvariant_cast<qreal>(0.0)); + frontState->assignProperty(selectionItem, "visible", true); + backState->assignProperty(pad, "fill", true); + backState->assignProperty(backItem, "visible", true); + backState->assignProperty(xRotation, "angle", qvariant_cast<qreal>(0.0)); + backState->assignProperty(yRotation, "angle", qvariant_cast<qreal>(0.0)); + backState->assignProperty(flipRotation, "angle", qvariant_cast<qreal>(180.0)); + backState->assignProperty(selectionItem, "visible", false); + stateMachine->addDefaultAnimation(smoothXRotation); + stateMachine->addDefaultAnimation(smoothYRotation); + stateMachine->addDefaultAnimation(smoothXSelection); + stateMachine->addDefaultAnimation(smoothYSelection); + stateMachine->setInitialState(splashState); +//! [10] + +//! [11] + // Transitions + QEventTransition *anyKeyTransition = new QEventTransition(this, QEvent::KeyPress, splashState); + anyKeyTransition->setTargetState(frontState); + anyKeyTransition->addAnimation(smoothSplashMove); + anyKeyTransition->addAnimation(smoothSplashOpacity); +//! [11] + +//! [12] + QKeyEventTransition *enterTransition = new QKeyEventTransition(this, QEvent::KeyPress, + Qt::Key_Enter, backState); + QKeyEventTransition *returnTransition = new QKeyEventTransition(this, QEvent::KeyPress, + Qt::Key_Return, backState); + QKeyEventTransition *backEnterTransition = new QKeyEventTransition(this, QEvent::KeyPress, + Qt::Key_Enter, frontState); + QKeyEventTransition *backReturnTransition = new QKeyEventTransition(this, QEvent::KeyPress, + Qt::Key_Return, frontState); + enterTransition->setTargetState(historyState); + returnTransition->setTargetState(historyState); + backEnterTransition->setTargetState(backState); + backReturnTransition->setTargetState(backState); + enterTransition->addAnimation(flipAnimation); + returnTransition->addAnimation(flipAnimation); + backEnterTransition->addAnimation(flipAnimation); + backReturnTransition->addAnimation(flipAnimation); +//! [12] + +//! [13] + // Create substates for each icon; store in temporary grid. + int columns = size.width(); + int rows = size.height(); + QVector< QVector< QState * > > stateGrid; + stateGrid.resize(rows); + for (int y = 0; y < rows; ++y) { + stateGrid[y].resize(columns); + for (int x = 0; x < columns; ++x) + stateGrid[y][x] = new QState(frontState); + } + frontState->setInitialState(stateGrid[0][0]); + selectionItem->setPos(pad->iconAt(0, 0)->pos()); +//! [13] + +//! [14] + // Enable key navigation using state transitions + for (int y = 0; y < rows; ++y) { + for (int x = 0; x < columns; ++x) { + QState *state = stateGrid[y][x]; + QKeyEventTransition *rightTransition = new QKeyEventTransition(this, QEvent::KeyPress, + Qt::Key_Right, state); + QKeyEventTransition *leftTransition = new QKeyEventTransition(this, QEvent::KeyPress, + Qt::Key_Left, state); + QKeyEventTransition *downTransition = new QKeyEventTransition(this, QEvent::KeyPress, + Qt::Key_Down, state); + QKeyEventTransition *upTransition = new QKeyEventTransition(this, QEvent::KeyPress, + Qt::Key_Up, state); + rightTransition->setTargetState(stateGrid[y][(x + 1) % columns]); + leftTransition->setTargetState(stateGrid[y][((x - 1) + columns) % columns]); + downTransition->setTargetState(stateGrid[(y + 1) % rows][x]); + upTransition->setTargetState(stateGrid[((y - 1) + rows) % rows][x]); +//! [14] +//! [15] + RoundRectItem *icon = pad->iconAt(x, y); + state->assignProperty(xRotation, "angle", -icon->x() / 6.0); + state->assignProperty(yRotation, "angle", icon->y() / 6.0); + state->assignProperty(selectionItem, "x", icon->x()); + state->assignProperty(selectionItem, "y", icon->y()); + frontState->assignProperty(icon, "visible", true); + backState->assignProperty(icon, "visible", false); + + QPropertyAnimation *setIconVisibleAnimation = new QPropertyAnimation(icon, "visible"); + setIconVisibleAnimation->setDuration(0); + setVariablesSequence->addAnimation(setIconVisibleAnimation); + } + } +//! [15] + +//! [16] + // Scene + QGraphicsScene *scene = new QGraphicsScene(this); + scene->setBackgroundBrush(QPixmap(":/images/blue_angle_swirl.jpg")); + scene->setItemIndexMethod(QGraphicsScene::NoIndex); + scene->addItem(pad); + scene->setSceneRect(scene->itemsBoundingRect()); + setScene(scene); +//! [16] + +//! [17] + // Adjust splash item to scene contents + const QRectF sbr = splash->boundingRect(); + splash->setPos(-sbr.width() / 2, scene->sceneRect().top() - 2); + frontState->assignProperty(splash, "y", splash->y() - 100.0); + scene->addItem(splash); +//! [17] + +//! [18] + // View + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setMinimumSize(50, 50); + setViewportUpdateMode(FullViewportUpdate); + setCacheMode(CacheBackground); + setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing); +#ifndef QT_NO_OPENGL + setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); +#endif + + stateMachine->start(); +//! [18] +} + +//! [19] +void PadNavigator::resizeEvent(QResizeEvent *event) +{ + QGraphicsView::resizeEvent(event); + fitInView(scene()->sceneRect(), Qt::KeepAspectRatio); +} +//! [19] diff --git a/examples/widgets/graphicsview/padnavigator/padnavigator.desktop b/examples/widgets/graphicsview/padnavigator/padnavigator.desktop new file mode 100644 index 0000000000..f0490730c6 --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/padnavigator.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Pad Navigator +Exec=/opt/usr/bin/padnavigator +Icon=padnavigator +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/graphicsview/padnavigator/padnavigator.h b/examples/widgets/graphicsview/padnavigator/padnavigator.h new file mode 100644 index 0000000000..659b901f5c --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/padnavigator.h @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PADNAVIGATOR_H +#define PADNAVIGATOR_H + +#include <QGraphicsView> +#include "ui_form.h" + +QT_BEGIN_NAMESPACE + +class QState; +class QStateMachine; +class Ui_Form; + +QT_END_NAMESPACE + +//! [0] +class PadNavigator : public QGraphicsView +{ + Q_OBJECT +public: + explicit PadNavigator(const QSize &size, QWidget *parent = 0); + +protected: + void resizeEvent(QResizeEvent *event); + +private: + Ui_Form form; +}; +//! [0] + +#endif // PADNAVIGATOR_H diff --git a/examples/widgets/graphicsview/padnavigator/padnavigator.pro b/examples/widgets/graphicsview/padnavigator/padnavigator.pro new file mode 100644 index 0000000000..4b9733bb9b --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/padnavigator.pro @@ -0,0 +1,28 @@ +SOURCES += main.cpp \ + roundrectitem.cpp \ + flippablepad.cpp \ + padnavigator.cpp \ + splashitem.cpp + +HEADERS += \ + roundrectitem.h \ + flippablepad.h \ + padnavigator.h \ + splashitem.h + +RESOURCES += \ + padnavigator.qrc + +FORMS += \ + form.ui + +QT += widgets +contains(QT_CONFIG, opengl):QT += opengl + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/padnavigator +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS padnavigator.pro images +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/padnavigator +INSTALLS += target sources + +CONFIG += console diff --git a/examples/widgets/graphicsview/padnavigator/padnavigator.qrc b/examples/widgets/graphicsview/padnavigator/padnavigator.qrc new file mode 100644 index 0000000000..b26ab92ae1 --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/padnavigator.qrc @@ -0,0 +1,13 @@ +<RCC> + <qresource> + <file>images/blue_angle_swirl.jpg</file> + <file>images/artsfftscope.png</file> + <file>images/kontact_contacts.png</file> + <file>images/kontact_journal.png</file> + <file>images/kontact_mail.png</file> + <file>images/kontact_notes.png</file> + <file>images/kopeteavailable.png</file> + <file>images/metacontact_online.png</file> + <file>images/minitools.png</file> + </qresource> +</RCC> diff --git a/examples/widgets/graphicsview/padnavigator/roundrectitem.cpp b/examples/widgets/graphicsview/padnavigator/roundrectitem.cpp new file mode 100644 index 0000000000..1438db3a9c --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/roundrectitem.cpp @@ -0,0 +1,113 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "roundrectitem.h" + +#include <QtWidgets/QtWidgets> + +//! [0] +RoundRectItem::RoundRectItem(const QRectF &bounds, const QColor &color, + QGraphicsItem *parent) + : QGraphicsObject(parent), fillRect(false), bounds(bounds) +{ + gradient.setStart(bounds.topLeft()); + gradient.setFinalStop(bounds.bottomRight()); + gradient.setColorAt(0, color); + gradient.setColorAt(1, color.dark(200)); + setCacheMode(ItemCoordinateCache); +} +//! [0] + +//! [1] +QPixmap RoundRectItem::pixmap() const +{ + return pix; +} +void RoundRectItem::setPixmap(const QPixmap &pixmap) +{ + pix = pixmap; + update(); +} +//! [1] + +//! [2] +QRectF RoundRectItem::boundingRect() const +{ + return bounds.adjusted(0, 0, 2, 2); +} +//! [2] + +//! [3] +void RoundRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, + QWidget *widget) +{ + Q_UNUSED(option); + Q_UNUSED(widget); + painter->setPen(Qt::NoPen); + painter->setBrush(QColor(0, 0, 0, 64)); + painter->drawRoundRect(bounds.translated(2, 2)); +//! [3] +//! [4] + if (fillRect) + painter->setBrush(QApplication::palette().brush(QPalette::Window)); + else + painter->setBrush(gradient); + painter->setPen(QPen(Qt::black, 1)); + painter->drawRoundRect(bounds); +//! [4] +//! [5] + if (!pix.isNull()) { + painter->scale(1.95, 1.95); + painter->drawPixmap(-pix.width() / 2, -pix.height() / 2, pix); + } +} +//! [5] + +//! [6] +bool RoundRectItem::fill() const +{ + return fillRect; +} +void RoundRectItem::setFill(bool fill) +{ + fillRect = fill; + update(); +} +//! [6] diff --git a/examples/widgets/graphicsview/padnavigator/roundrectitem.h b/examples/widgets/graphicsview/padnavigator/roundrectitem.h new file mode 100644 index 0000000000..af84984d49 --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/roundrectitem.h @@ -0,0 +1,75 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ROUNDRECTITEM_H +#define ROUNDRECTITEM_H + +#include <QGraphicsObject> +#include <QLinearGradient> + +//! [0] +class RoundRectItem : public QGraphicsObject +{ + Q_OBJECT + Q_PROPERTY(bool fill READ fill WRITE setFill) +public: + RoundRectItem(const QRectF &bounds, const QColor &color, + QGraphicsItem *parent = 0); + + QPixmap pixmap() const; + void setPixmap(const QPixmap &pixmap); + + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); + + bool fill() const; + void setFill(bool fill); +//! [0] + +//! [1] +private: + QPixmap pix; + bool fillRect; + QRectF bounds; + QLinearGradient gradient; +}; +//! [1] + +#endif // ROUNDRECTITEM_H diff --git a/examples/widgets/graphicsview/padnavigator/splashitem.cpp b/examples/widgets/graphicsview/padnavigator/splashitem.cpp new file mode 100644 index 0000000000..d87e8333bd --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/splashitem.cpp @@ -0,0 +1,83 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "splashitem.h" + +#include <QtWidgets/QtWidgets> + +//! [0] +SplashItem::SplashItem(QGraphicsItem *parent) + : QGraphicsObject(parent) +{ + text = tr("Welcome to the Pad Navigator Example. You can use the" + " keyboard arrows to navigate the icons, and press enter" + " to activate an item. Press any key to begin."); + setCacheMode(DeviceCoordinateCache); +} +//! [0] + +//! [1] +QRectF SplashItem::boundingRect() const +{ + return QRectF(0, 0, 400, 175); +} +//! [1] + +//! [2] +void SplashItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, + QWidget *widget) +{ + Q_UNUSED(option); + Q_UNUSED(widget); + painter->setPen(QPen(Qt::black, 2)); + painter->setBrush(QColor(245, 245, 255, 220)); + painter->setClipRect(boundingRect()); + painter->drawRoundRect(3, -100 + 3, 400 - 6, 250 - 6); + + QRectF textRect = boundingRect().adjusted(10, 10, -10, -10); + int flags = Qt::AlignTop | Qt::AlignLeft | Qt::TextWordWrap; + + QFont font; + font.setPixelSize(18); + painter->setPen(Qt::black); + painter->setFont(font); + painter->drawText(textRect, flags, text); +} +//! [2] diff --git a/examples/widgets/graphicsview/padnavigator/splashitem.h b/examples/widgets/graphicsview/padnavigator/splashitem.h new file mode 100644 index 0000000000..bc0917e3de --- /dev/null +++ b/examples/widgets/graphicsview/padnavigator/splashitem.h @@ -0,0 +1,61 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SPLASHITEM_H +#define SPLASHITEM_H + +#include <QGraphicsObject> + +//! [0] +class SplashItem : public QGraphicsObject +{ + Q_OBJECT +public: + explicit SplashItem(QGraphicsItem *parent = 0); + + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); + +private: + QString text; +}; +//! [0] + +#endif // SPLASHITEM_H diff --git a/examples/widgets/graphicsview/portedasteroids/portedasteroids.desktop b/examples/widgets/graphicsview/portedasteroids/portedasteroids.desktop new file mode 100644 index 0000000000..abd061699b --- /dev/null +++ b/examples/widgets/graphicsview/portedasteroids/portedasteroids.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Ported Asteroids +Exec=/opt/usr/bin/portedasteroids +Icon=portedasteroids +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/graphicsview/portedcanvas/portedcanvas.desktop b/examples/widgets/graphicsview/portedcanvas/portedcanvas.desktop new file mode 100644 index 0000000000..1217dc43de --- /dev/null +++ b/examples/widgets/graphicsview/portedcanvas/portedcanvas.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Ported Canvas +Exec=/opt/usr/bin/portedcanvas +Icon=portedcanvas +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/graphicsview/simpleanchorlayout/main.cpp b/examples/widgets/graphicsview/simpleanchorlayout/main.cpp new file mode 100644 index 0000000000..50d8513c84 --- /dev/null +++ b/examples/widgets/graphicsview/simpleanchorlayout/main.cpp @@ -0,0 +1,134 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtWidgets> + +class Widget : public QGraphicsWidget +{ +public: + Widget(const QColor &color, const QColor &textColor, const QString &caption, + QGraphicsItem *parent = 0) + : QGraphicsWidget(parent), caption(caption), color(color), textColor(textColor) + { + } + + void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget * = 0) + { + QFont font; + font.setPixelSize(0.75 * qMin(boundingRect().width(), boundingRect().height())); + + painter->fillRect(boundingRect(), color); + painter->save(); + painter->setFont(font); + painter->setPen(textColor); + painter->drawText(boundingRect(), Qt::AlignCenter, caption); + painter->restore(); + } + +private: + QString caption; + QColor color; + QColor textColor; +}; + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QGraphicsScene *scene = new QGraphicsScene(); + + Widget *a = new Widget(Qt::blue, Qt::white, "a"); + a->setPreferredSize(100, 100); + Widget *b = new Widget(Qt::green, Qt::black, "b"); + b->setPreferredSize(100, 100); + Widget *c = new Widget(Qt::red, Qt::black, "c"); + c->setPreferredSize(100, 100); + + QGraphicsAnchorLayout *layout = new QGraphicsAnchorLayout(); +/* + //! [adding a corner anchor in two steps] + layout->addAnchor(a, Qt::AnchorTop, layout, Qt::AnchorTop); + layout->addAnchor(a, Qt::AnchorLeft, layout, Qt::AnchorLeft); + //! [adding a corner anchor in two steps] +*/ + //! [adding a corner anchor] + layout->addCornerAnchors(a, Qt::TopLeftCorner, layout, Qt::TopLeftCorner); + //! [adding a corner anchor] + + //! [adding anchors] + layout->addAnchor(b, Qt::AnchorLeft, a, Qt::AnchorRight); + layout->addAnchor(b, Qt::AnchorTop, a, Qt::AnchorBottom); + //! [adding anchors] + + // Place a third widget below the second. + layout->addAnchor(b, Qt::AnchorBottom, c, Qt::AnchorTop); + +/* + //! [adding anchors to match sizes in two steps] + layout->addAnchor(b, Qt::AnchorLeft, c, Qt::AnchorLeft); + layout->addAnchor(b, Qt::AnchorRight, c, Qt::AnchorRight); + //! [adding anchors to match sizes in two steps] +*/ + + //! [adding anchors to match sizes] + layout->addAnchors(b, c, Qt::Horizontal); + //! [adding anchors to match sizes] + + // Anchor the bottom-right corner of the third widget to the bottom-right + // corner of the layout. + layout->addCornerAnchors(c, Qt::BottomRightCorner, layout, Qt::BottomRightCorner); + + QGraphicsWidget *w = new QGraphicsWidget(0, Qt::Window | Qt::CustomizeWindowHint | Qt::WindowTitleHint); + w->setPos(20, 20); + w->setMinimumSize(100, 100); + w->setPreferredSize(320, 240); + w->setLayout(layout); + w->setWindowTitle(QApplication::translate("simpleanchorlayout", "QGraphicsAnchorLayout in use")); + scene->addItem(w); + + QGraphicsView *view = new QGraphicsView(); + view->setScene(scene); + view->setWindowTitle(QApplication::translate("simpleanchorlayout", "Simple Anchor Layout")); + + view->resize(360, 320); + view->show(); + + return app.exec(); +} diff --git a/examples/widgets/graphicsview/simpleanchorlayout/simpleanchorlayout.desktop b/examples/widgets/graphicsview/simpleanchorlayout/simpleanchorlayout.desktop new file mode 100644 index 0000000000..0e8d73a859 --- /dev/null +++ b/examples/widgets/graphicsview/simpleanchorlayout/simpleanchorlayout.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Simple Anchor Layout +Exec=/opt/usr/bin/simpleanchorlayout +Icon=simpleanchorlayout +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/graphicsview/simpleanchorlayout/simpleanchorlayout.pro b/examples/widgets/graphicsview/simpleanchorlayout/simpleanchorlayout.pro new file mode 100644 index 0000000000..b044d4e91c --- /dev/null +++ b/examples/widgets/graphicsview/simpleanchorlayout/simpleanchorlayout.pro @@ -0,0 +1,12 @@ +SOURCES = main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/simpleanchorlayout +sources.files = $$SOURCES $$HEADERS $$RESOURCES simpleanchorlayout.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/simpleanchorlayout +INSTALLS += target sources + +TARGET = simpleanchorlayout +QT += widgets + +simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/graphicsview/weatheranchorlayout/images/5days.jpg b/examples/widgets/graphicsview/weatheranchorlayout/images/5days.jpg Binary files differnew file mode 100644 index 0000000000..fd92ba8ba7 --- /dev/null +++ b/examples/widgets/graphicsview/weatheranchorlayout/images/5days.jpg diff --git a/examples/widgets/graphicsview/weatheranchorlayout/images/details.jpg b/examples/widgets/graphicsview/weatheranchorlayout/images/details.jpg Binary files differnew file mode 100644 index 0000000000..fde0448c69 --- /dev/null +++ b/examples/widgets/graphicsview/weatheranchorlayout/images/details.jpg diff --git a/examples/widgets/graphicsview/weatheranchorlayout/images/place.jpg b/examples/widgets/graphicsview/weatheranchorlayout/images/place.jpg Binary files differnew file mode 100644 index 0000000000..03e5344330 --- /dev/null +++ b/examples/widgets/graphicsview/weatheranchorlayout/images/place.jpg diff --git a/examples/widgets/graphicsview/weatheranchorlayout/images/tabbar.jpg b/examples/widgets/graphicsview/weatheranchorlayout/images/tabbar.jpg Binary files differnew file mode 100644 index 0000000000..7777662901 --- /dev/null +++ b/examples/widgets/graphicsview/weatheranchorlayout/images/tabbar.jpg diff --git a/examples/widgets/graphicsview/weatheranchorlayout/images/title.jpg b/examples/widgets/graphicsview/weatheranchorlayout/images/title.jpg Binary files differnew file mode 100644 index 0000000000..fa84c8156c --- /dev/null +++ b/examples/widgets/graphicsview/weatheranchorlayout/images/title.jpg diff --git a/examples/widgets/graphicsview/weatheranchorlayout/images/weather-few-clouds.png b/examples/widgets/graphicsview/weatheranchorlayout/images/weather-few-clouds.png Binary files differnew file mode 100644 index 0000000000..eea6ce6529 --- /dev/null +++ b/examples/widgets/graphicsview/weatheranchorlayout/images/weather-few-clouds.png diff --git a/examples/widgets/graphicsview/weatheranchorlayout/main.cpp b/examples/widgets/graphicsview/weatheranchorlayout/main.cpp new file mode 100644 index 0000000000..64605bebc0 --- /dev/null +++ b/examples/widgets/graphicsview/weatheranchorlayout/main.cpp @@ -0,0 +1,274 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QLabel> +#include <QPainter> +#include <QPushButton> +#include <QApplication> + +#include <QGraphicsView> +#include <QGraphicsScene> +#include <QGraphicsWidget> +#include <QGraphicsProxyWidget> +#include <QGraphicsAnchorLayout> +#include <QGraphicsSceneResizeEvent> + + +class GraphicsView : public QGraphicsView +{ +public: + GraphicsView(QGraphicsScene *scene, QGraphicsWidget *widget) : QGraphicsView(scene), w(widget) + { + } + + virtual void resizeEvent(QResizeEvent *event) + { + w->setGeometry(0, 0, event->size().width(), event->size().height()); + } + + QGraphicsWidget *w; +}; + +class PixmapWidget : public QGraphicsLayoutItem +{ + +public: + PixmapWidget(const QPixmap &pix) : QGraphicsLayoutItem() + { + original = new QGraphicsPixmapItem(pix); + setGraphicsItem(original); + original->show(); + r = QRectF(QPointF(0, 0), pix.size()); + } + + ~PixmapWidget() + { + setGraphicsItem(0); + delete original; + } + + void setZValue(qreal z) + { + original->setZValue(z); + } + + void setGeometry (const QRectF &rect) + { + original->setTransform(QTransform::fromScale(rect.width() / r.width(), rect.height() / r.height()), true); + original->setPos(rect.x(), rect.y()); + r = rect; + } + +protected: + QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const + { + Q_UNUSED(constraint); + QSizeF sh; + switch (which) { + case Qt::MinimumSize: + sh = QSizeF(0, 0); + break; + case Qt::PreferredSize: + sh = QSizeF(50, 50); + break; + case Qt::MaximumSize: + sh = QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); + break; + default: + break; + } + return sh; + } + +private: + QGraphicsPixmapItem *original; + QRectF r; +}; + + +class PlaceWidget : public QGraphicsWidget +{ + Q_OBJECT + +public: + PlaceWidget(const QPixmap &pix) : QGraphicsWidget(), original(pix), scaled(pix) + { + } + + void paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget*) + { + QPointF reflection = QPointF(); + reflection.setY(scaled.height() + 2); + + painter->drawPixmap(QPointF(), scaled); + + QPixmap tmp(scaled.size()); + tmp.fill(Qt::transparent); + QPainter p(&tmp); + + // create gradient + QPoint p1(scaled.width() / 2, 0); + QPoint p2(scaled.width() / 2, scaled.height()); + QLinearGradient linearGrad(p1, p2); + linearGrad.setColorAt(0, QColor(0, 0, 0, 0)); + linearGrad.setColorAt(0.65, QColor(0, 0, 0, 127)); + linearGrad.setColorAt(1, QColor(0, 0, 0, 255)); + + // apply 'mask' + p.setBrush(linearGrad); + p.fillRect(0, 0, tmp.width(), tmp.height(), QBrush(linearGrad)); + p.fillRect(0, 0, tmp.width(), tmp.height(), QBrush(linearGrad)); + + // paint the image flipped + p.setCompositionMode(QPainter::CompositionMode_DestinationOver); + p.drawPixmap(0, 0, QPixmap::fromImage(scaled.toImage().mirrored(false, true))); + p.end(); + + painter->drawPixmap(reflection, tmp); + } + + void resizeEvent(QGraphicsSceneResizeEvent *event) + { + QSize newSize = event->newSize().toSize(); + newSize.setHeight(newSize.height() / 2); + scaled = original.scaled(newSize); + } + + QRectF boundingRect() const + { + QSize size(scaled.width(), scaled.height() * 2 + 2); + return QRectF(QPointF(0, 0), size); + } + +private: + QPixmap original; + QPixmap scaled; +}; + + +int main(int argc, char **argv) +{ + Q_INIT_RESOURCE(weatheranchorlayout); + + QApplication app(argc, argv); + + QGraphicsScene scene; + scene.setSceneRect(0, 0, 800, 480); + + // pixmaps widgets + PixmapWidget *title = new PixmapWidget(QPixmap(":/images/title.jpg")); + PlaceWidget *place = new PlaceWidget(QPixmap(":/images/place.jpg")); + PixmapWidget *details = new PixmapWidget(QPixmap(":/images/5days.jpg")); + PixmapWidget *sunnyWeather = new PixmapWidget(QPixmap(":/images/weather-few-clouds.png")); + PixmapWidget *tabbar = new PixmapWidget(QPixmap(":/images/tabbar.jpg")); + + + // setup sizes + title->setPreferredSize(QSizeF(348, 45)); + title->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + + place->setPreferredSize(QSizeF(96, 72)); + place->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + + details->setMinimumSize(QSizeF(200, 112)); + details->setPreferredSize(QSizeF(200, 112)); + details->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + + tabbar->setPreferredSize(QSizeF(70, 24)); + tabbar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + + sunnyWeather->setPreferredSize(QSizeF(128, 97)); + sunnyWeather->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + sunnyWeather->setZValue(9999); + + // start anchor layout + QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout; + l->setSpacing(0); + + // setup the main widget + QGraphicsWidget *w = new QGraphicsWidget(0, Qt::Window); + QPalette p; + p.setColor(QPalette::Window, Qt::black); + w->setPalette(p); + w->setPos(20, 20); + w->setLayout(l); + + // vertical anchors + QGraphicsAnchor *anchor = l->addAnchor(title, Qt::AnchorTop, l, Qt::AnchorTop); + anchor = l->addAnchor(place, Qt::AnchorTop, title, Qt::AnchorBottom); + anchor->setSpacing(12); + anchor = l->addAnchor(place, Qt::AnchorBottom, l, Qt::AnchorBottom); + anchor->setSpacing(12); + + anchor = l->addAnchor(sunnyWeather, Qt::AnchorTop, title, Qt::AnchorTop); + anchor = l->addAnchor(sunnyWeather, Qt::AnchorBottom, l, Qt::AnchorVerticalCenter); + + anchor = l->addAnchor(tabbar, Qt::AnchorTop, title, Qt::AnchorBottom); + anchor->setSpacing(5); + anchor = l->addAnchor(details, Qt::AnchorTop, tabbar, Qt::AnchorBottom); + anchor->setSpacing(2); + anchor = l->addAnchor(details, Qt::AnchorBottom, l, Qt::AnchorBottom); + anchor->setSpacing(12); + + // horizontal anchors + anchor = l->addAnchor(l, Qt::AnchorLeft, title, Qt::AnchorLeft); + anchor = l->addAnchor(title, Qt::AnchorRight, l, Qt::AnchorRight); + + anchor = l->addAnchor(place, Qt::AnchorLeft, l, Qt::AnchorLeft); + anchor->setSpacing(15); + anchor = l->addAnchor(place, Qt::AnchorRight, details, Qt::AnchorLeft); + anchor->setSpacing(35); + + anchor = l->addAnchor(sunnyWeather, Qt::AnchorLeft, place, Qt::AnchorHorizontalCenter); + anchor = l->addAnchor(sunnyWeather, Qt::AnchorRight, l, Qt::AnchorHorizontalCenter); + + anchor = l->addAnchor(tabbar, Qt::AnchorHorizontalCenter, details, Qt::AnchorHorizontalCenter); + anchor = l->addAnchor(details, Qt::AnchorRight, l, Qt::AnchorRight); + + // QGV setup + scene.addItem(w); + scene.setBackgroundBrush(Qt::white); + QGraphicsView *view = new QGraphicsView(&scene); + view->show(); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/widgets/graphicsview/weatheranchorlayout/weatheranchorlayout.desktop b/examples/widgets/graphicsview/weatheranchorlayout/weatheranchorlayout.desktop new file mode 100644 index 0000000000..0c6ab89a68 --- /dev/null +++ b/examples/widgets/graphicsview/weatheranchorlayout/weatheranchorlayout.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Encoding=UTF-8 +Version=1.0 +Type=Application +Terminal=false +Name=Weather Anchor Layout +Exec=/opt/usr/bin/weatheranchorlayout +Icon=weatheranchorlayout +X-Window-Icon= +X-HildonDesk-ShowInToolbar=true +X-Osso-Type=application/x-executable diff --git a/examples/widgets/graphicsview/weatheranchorlayout/weatheranchorlayout.pro b/examples/widgets/graphicsview/weatheranchorlayout/weatheranchorlayout.pro new file mode 100644 index 0000000000..b6eb292a12 --- /dev/null +++ b/examples/widgets/graphicsview/weatheranchorlayout/weatheranchorlayout.pro @@ -0,0 +1,12 @@ +QT += widgets + +SOURCES += main.cpp +RESOURCES += weatheranchorlayout.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/weatheranchorlayout +sources.files = $$SOURCES $$HEADERS $$RESOURCES weatheranchorlayout.pro images +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/graphicsview/weatheranchorlayout +INSTALLS += target sources + +simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/graphicsview/weatheranchorlayout/weatheranchorlayout.qrc b/examples/widgets/graphicsview/weatheranchorlayout/weatheranchorlayout.qrc new file mode 100644 index 0000000000..e39f8c0423 --- /dev/null +++ b/examples/widgets/graphicsview/weatheranchorlayout/weatheranchorlayout.qrc @@ -0,0 +1,10 @@ +<!DOCTYPE RCC><RCC version="1.0"> +<qresource> + <file>images/5days.jpg</file> + <file>images/title.jpg</file> + <file>images/place.jpg</file> + <file>images/tabbar.jpg</file> + <file>images/details.jpg</file> + <file>images/weather-few-clouds.png</file> +</qresource> +</RCC> |