summaryrefslogtreecommitdiffstats
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/corelib/mimetypes/mimetypebrowser/mimetypemodel.cpp4
-rw-r--r--examples/corelib/serialization/convert/cborconverter.cpp2
-rw-r--r--examples/corelib/serialization/convert/datastreamconverter.cpp2
-rw-r--r--examples/corelib/serialization/convert/jsonconverter.cpp60
-rw-r--r--examples/corelib/serialization/convert/jsonconverter.h13
-rw-r--r--examples/corelib/serialization/convert/xmlconverter.cpp6
-rw-r--r--examples/corelib/serialization/savegame/doc/src/savegame.qdoc8
-rw-r--r--examples/corelib/serialization/savegame/game.cpp11
-rw-r--r--examples/corelib/threads/doc/src/mandelbrot.qdoc10
-rw-r--r--examples/corelib/tools/customtype/main.cpp2
-rw-r--r--examples/embedded/flightinfo/flightinfo.cpp2
-rw-r--r--examples/embedded/lightmaps/slippymap.cpp2
-rw-r--r--examples/network/bearermonitor/bearermonitor.cpp53
-rw-r--r--examples/network/bearermonitor/bearermonitor.h9
-rw-r--r--examples/network/bearermonitor/main.cpp4
-rw-r--r--examples/network/bearermonitor/sessionwidget.cpp28
-rw-r--r--examples/network/bearermonitor/sessionwidget.h10
-rw-r--r--examples/network/blockingfortuneclient/blockingclient.cpp39
-rw-r--r--examples/network/blockingfortuneclient/blockingclient.h2
-rw-r--r--examples/network/blockingfortuneclient/fortunethread.cpp4
-rw-r--r--examples/network/blockingfortuneclient/fortunethread.h2
-rw-r--r--examples/network/broadcastreceiver/receiver.cpp13
-rw-r--r--examples/network/dnslookup/dnslookup.cpp4
-rw-r--r--examples/network/doc/src/blockingfortuneclient.qdoc7
-rw-r--r--examples/network/download/main.cpp10
-rw-r--r--examples/network/downloadmanager/downloadmanager.cpp18
-rw-r--r--examples/network/downloadmanager/main.cpp3
-rw-r--r--examples/network/googlesuggest/googlesuggest.cpp18
-rw-r--r--examples/network/googlesuggest/searchbox.cpp8
-rw-r--r--examples/network/http/httpwindow.cpp2
-rw-r--r--examples/network/multicastreceiver/receiver.cpp10
-rw-r--r--examples/network/multistreamclient/client.cpp4
-rw-r--r--examples/network/network-chat/chatdialog.cpp16
-rw-r--r--examples/network/network-chat/chatdialog.h2
-rw-r--r--examples/network/network-chat/client.cpp20
-rw-r--r--examples/network/network-chat/connection.cpp13
-rw-r--r--examples/network/network-chat/connection.h4
-rw-r--r--examples/network/network-chat/peermanager.cpp8
-rw-r--r--examples/network/network-chat/server.h2
-rw-r--r--examples/network/network.pro2
-rw-r--r--examples/network/securesocketclient/main.cpp4
-rw-r--r--examples/network/securesocketclient/sslclient.cpp37
-rw-r--r--examples/network/threadedfortuneserver/dialog.cpp2
-rw-r--r--examples/network/threadedfortuneserver/dialog.h2
-rw-r--r--examples/network/threadedfortuneserver/fortuneserver.cpp2
-rw-r--r--examples/network/threadedfortuneserver/fortuneserver.h2
-rw-r--r--examples/network/threadedfortuneserver/fortunethread.cpp2
-rw-r--r--examples/network/torrent/addtorrentdialog.cpp12
-rw-r--r--examples/network/torrent/addtorrentdialog.h2
-rw-r--r--examples/network/torrent/filemanager.h2
-rw-r--r--examples/network/torrent/mainwindow.cpp92
-rw-r--r--examples/network/torrent/mainwindow.h2
-rw-r--r--examples/network/torrent/peerwireclient.cpp34
-rw-r--r--examples/network/torrent/peerwireclient.h2
-rw-r--r--examples/network/torrent/ratecontroller.cpp6
-rw-r--r--examples/network/torrent/ratecontroller.h9
-rw-r--r--examples/network/torrent/torrentclient.cpp90
-rw-r--r--examples/network/torrent/torrentclient.h5
-rw-r--r--examples/network/torrent/torrentserver.cpp10
-rw-r--r--examples/network/torrent/trackerclient.cpp18
-rw-r--r--examples/network/torrent/trackerclient.h16
-rw-r--r--examples/opengl/2dpainting/2dpainting.pro2
-rw-r--r--examples/opengl/computegles31/computegles31.pro2
-rw-r--r--examples/opengl/computegles31/glwindow.cpp6
-rw-r--r--examples/opengl/cube/cube.pro2
-rw-r--r--examples/opengl/hellogl2/hellogl2.pro2
-rw-r--r--examples/opengl/hellogles3/hellogles3.pro2
-rw-r--r--examples/opengl/qopenglwidget/qopenglwidget.pro2
-rw-r--r--examples/opengl/qopenglwindow/qopenglwindow.pro1
-rw-r--r--examples/opengl/textures/textures.pro2
-rw-r--r--examples/opengl/threadedqopenglwidget/threadedqopenglwidget.pro2
-rw-r--r--examples/sql/doc/src/cachedtable.qdoc8
-rw-r--r--examples/sql/masterdetail/mainwindow.cpp2
-rw-r--r--examples/widgets/animation/sub-attaq/mainwindow.cpp14
-rw-r--r--examples/widgets/animation/sub-attaq/sub-attaq.pro1
-rw-r--r--examples/widgets/desktop/systray/doc/src/systray.qdoc4
-rw-r--r--examples/widgets/dialogs/standarddialogs/dialog.cpp2
-rw-r--r--examples/widgets/doc/src/addressbook-tutorial.qdoc2
-rw-r--r--examples/widgets/doc/src/customsortfiltermodel.qdoc4
-rw-r--r--examples/widgets/doc/src/gallery.qdoc (renamed from examples/xml/saxbookmarks/doc/src/saxbookmarks.qdoc)19
-rw-r--r--examples/widgets/doc/src/icons.qdoc38
-rw-r--r--examples/widgets/doc/src/padnavigator.qdoc21
-rw-r--r--examples/widgets/doc/src/shapedclock.qdoc52
-rw-r--r--examples/widgets/doc/src/styles.qdoc10
-rw-r--r--examples/widgets/doc/src/transformations.qdoc4
-rw-r--r--examples/widgets/gallery/gallery.pro10
-rw-r--r--examples/widgets/gallery/main.cpp (renamed from examples/xml/saxbookmarks/main.cpp)25
-rw-r--r--examples/widgets/gallery/widgetgallery.cpp474
-rw-r--r--examples/widgets/gallery/widgetgallery.h (renamed from examples/xml/saxbookmarks/mainwindow.h)44
-rw-r--r--examples/widgets/graphicsview/boxes/3rdparty/fbm.c207
-rw-r--r--examples/widgets/graphicsview/boxes/3rdparty/fbm.h40
-rw-r--r--examples/widgets/graphicsview/boxes/basic.fsh82
-rw-r--r--examples/widgets/graphicsview/boxes/basic.vsh70
-rw-r--r--examples/widgets/graphicsview/boxes/boxes.pro27
-rw-r--r--examples/widgets/graphicsview/boxes/boxes.qrc25
-rw-r--r--examples/widgets/graphicsview/boxes/cubemap_negx.jpgbin41060 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/cubemap_negy.jpgbin15520 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/cubemap_negz.jpgbin68911 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/cubemap_posx.jpgbin74915 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/cubemap_posy.jpgbin24193 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/cubemap_posz.jpgbin57881 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/dotted.fsh75
-rw-r--r--examples/widgets/graphicsview/boxes/fresnel.fsh88
-rw-r--r--examples/widgets/graphicsview/boxes/glass.fsh85
-rw-r--r--examples/widgets/graphicsview/boxes/glbuffers.cpp406
-rw-r--r--examples/widgets/graphicsview/boxes/glbuffers.h372
-rw-r--r--examples/widgets/graphicsview/boxes/glextensions.cpp107
-rw-r--r--examples/widgets/graphicsview/boxes/glextensions.h204
-rw-r--r--examples/widgets/graphicsview/boxes/gltrianglemesh.h99
-rw-r--r--examples/widgets/graphicsview/boxes/granite.fsh85
-rw-r--r--examples/widgets/graphicsview/boxes/main.cpp157
-rw-r--r--examples/widgets/graphicsview/boxes/marble.fsh80
-rw-r--r--examples/widgets/graphicsview/boxes/parameters.par5
-rw-r--r--examples/widgets/graphicsview/boxes/qt-logo.jpgbin20316 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/qt-logo.pngbin12167 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/qtbox.cpp470
-rw-r--r--examples/widgets/graphicsview/boxes/qtbox.h126
-rw-r--r--examples/widgets/graphicsview/boxes/reflection.fsh63
-rw-r--r--examples/widgets/graphicsview/boxes/refraction.fsh79
-rw-r--r--examples/widgets/graphicsview/boxes/roundedbox.cpp170
-rw-r--r--examples/widgets/graphicsview/boxes/roundedbox.h77
-rw-r--r--examples/widgets/graphicsview/boxes/scene.cpp1028
-rw-r--r--examples/widgets/graphicsview/boxes/scene.h247
-rw-r--r--examples/widgets/graphicsview/boxes/smiley.pngbin14508 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/square.jpgbin14542 -> 0 bytes
-rw-r--r--examples/widgets/graphicsview/boxes/trackball.cpp159
-rw-r--r--examples/widgets/graphicsview/boxes/trackball.h87
-rw-r--r--examples/widgets/graphicsview/boxes/wood.fsh79
-rw-r--r--examples/widgets/graphicsview/chip/chip.pro1
-rw-r--r--examples/widgets/graphicsview/chip/view.cpp21
-rw-r--r--examples/widgets/graphicsview/chip/view.h2
-rw-r--r--examples/widgets/graphicsview/embeddeddialogs/customproxy.h2
-rw-r--r--examples/widgets/graphicsview/graphicsview.pro4
-rw-r--r--examples/widgets/graphicsview/padnavigator/padnavigator.cpp8
-rw-r--r--examples/widgets/layouts/flowlayout/flowlayout.cpp2
-rw-r--r--examples/widgets/mainwindows/mainwindow/colorswatch.h2
-rw-r--r--examples/widgets/mainwindows/mainwindow/mainwindow.h2
-rw-r--r--examples/widgets/painting/shared/arthurwidgets.cpp4
-rw-r--r--examples/widgets/painting/shared/hoverpoints.cpp4
-rw-r--r--examples/widgets/painting/shared/shared.pri1
-rw-r--r--examples/widgets/tools/regularexpression/regularexpressiondialog.cpp2
-rw-r--r--examples/widgets/widgets.pro1
-rw-r--r--examples/widgets/widgets/charactermap/mainwindow.cpp2
-rw-r--r--examples/widgets/widgets/icons/mainwindow.cpp2
-rw-r--r--examples/widgets/widgets/shapedclock/shapedclock.cpp7
-rw-r--r--examples/widgets/widgets/styles/main.cpp3
-rw-r--r--examples/widgets/widgets/styles/norwegianwoodstyle.cpp75
-rw-r--r--examples/widgets/widgets/styles/norwegianwoodstyle.h4
-rw-r--r--examples/widgets/widgets/styles/widgetgallery.cpp48
-rw-r--r--examples/widgets/widgets/styles/widgetgallery.h6
-rw-r--r--examples/widgets/widgets/tablet/mainwindow.cpp6
-rw-r--r--examples/widgets/widgets/validators/localeselector.cpp2
-rw-r--r--examples/xml/dombookmarks/xbeltree.cpp2
-rw-r--r--examples/xml/saxbookmarks/CMakeLists.txt31
-rw-r--r--examples/xml/saxbookmarks/doc/images/saxbookmarks-example.pngbin26219 -> 0 bytes
-rw-r--r--examples/xml/saxbookmarks/jennifer.xbel69
-rw-r--r--examples/xml/saxbookmarks/mainwindow.cpp177
-rw-r--r--examples/xml/saxbookmarks/saxbookmarks.pro15
-rw-r--r--examples/xml/saxbookmarks/xbelgenerator.cpp124
-rw-r--r--examples/xml/saxbookmarks/xbelgenerator.h78
-rw-r--r--examples/xml/saxbookmarks/xbelhandler.cpp160
-rw-r--r--examples/xml/saxbookmarks/xbelhandler.h88
-rw-r--r--examples/xml/xml.pro1
163 files changed, 1104 insertions, 6196 deletions
diff --git a/examples/corelib/mimetypes/mimetypebrowser/mimetypemodel.cpp b/examples/corelib/mimetypes/mimetypebrowser/mimetypemodel.cpp
index f755e060c6..64732ba980 100644
--- a/examples/corelib/mimetypes/mimetypebrowser/mimetypemodel.cpp
+++ b/examples/corelib/mimetypes/mimetypebrowser/mimetypemodel.cpp
@@ -95,7 +95,7 @@ QVariant MimetypeModel::data(const QModelIndex &index, int role) const
if (role != Qt::DecorationRole || !index.isValid() || index.data(iconQueriedRole).toBool())
return QStandardItemModel::data(index, role);
QStandardItem *item = itemFromIndex(index);
- const QString iconName = item->data(mimeTypeRole).value<QMimeType>().iconName();
+ const QString iconName = qvariant_cast<QMimeType>(item->data(mimeTypeRole)).iconName();
if (!iconName.isEmpty())
item->setIcon(QIcon::fromTheme(iconName));
item->setData(QVariant(true), iconQueriedRole);
@@ -104,7 +104,7 @@ QVariant MimetypeModel::data(const QModelIndex &index, int role) const
QMimeType MimetypeModel::mimeType(const QModelIndex &index) const
{
- return index.data(mimeTypeRole).value<QMimeType>();
+ return qvariant_cast<QMimeType>(index.data(mimeTypeRole));
}
void MimetypeModel::populate()
diff --git a/examples/corelib/serialization/convert/cborconverter.cpp b/examples/corelib/serialization/convert/cborconverter.cpp
index f907bb0af6..60410ed26a 100644
--- a/examples/corelib/serialization/convert/cborconverter.cpp
+++ b/examples/corelib/serialization/convert/cborconverter.cpp
@@ -144,7 +144,7 @@ static QCborValue convertFromVariant(const QVariant &v, TrimFloatingPoint fpTrim
}
if (v.userType() == qMetaTypeId<VariantOrderedMap>()) {
- const auto m = v.value<VariantOrderedMap>();
+ const auto m = qvariant_cast<VariantOrderedMap>(v);
QCborMap map;
for (const auto &pair : m)
map.insert(convertFromVariant(pair.first, fpTrimming),
diff --git a/examples/corelib/serialization/convert/datastreamconverter.cpp b/examples/corelib/serialization/convert/datastreamconverter.cpp
index 7cdb844141..7e9f5e1bdc 100644
--- a/examples/corelib/serialization/convert/datastreamconverter.cpp
+++ b/examples/corelib/serialization/convert/datastreamconverter.cpp
@@ -98,7 +98,7 @@ static QString dumpVariant(const QVariant &v, const QString &indent = QLatin1Str
int type = v.userType();
if (type == qMetaTypeId<VariantOrderedMap>() || type == QVariant::Map) {
const auto map = (type == QVariant::Map) ?
- VariantOrderedMap(v.toMap()) : v.value<VariantOrderedMap>();
+ VariantOrderedMap(v.toMap()) : qvariant_cast<VariantOrderedMap>(v);
result = QLatin1String("Map {");
for (const auto &pair : map) {
diff --git a/examples/corelib/serialization/convert/jsonconverter.cpp b/examples/corelib/serialization/convert/jsonconverter.cpp
index 80d1cc6827..ec24af703d 100644
--- a/examples/corelib/serialization/convert/jsonconverter.cpp
+++ b/examples/corelib/serialization/convert/jsonconverter.cpp
@@ -57,7 +57,6 @@
#include <QJsonValue>
static JsonConverter jsonConverter;
-static BinaryJsonConverter BinaryJsonConverter;
static const char optionHelp[] =
"compact=no|yes Use compact JSON form.\n";
@@ -151,62 +150,3 @@ void JsonConverter::saveFile(QIODevice *f, const QVariant &contents, const QStri
f->write(convertFromVariant(contents).toJson(format));
}
-
-QString BinaryJsonConverter::name()
-{
- return "binary-json";
-}
-
-Converter::Direction BinaryJsonConverter::directions()
-{
- return InOut;
-}
-
-Converter::Options BinaryJsonConverter::outputOptions()
-{
- return {};
-}
-
-const char *BinaryJsonConverter::optionsHelp()
-{
- return nullptr;
-}
-
-bool BinaryJsonConverter::probeFile(QIODevice *f)
-{
- return f->isReadable() && f->peek(4) == "qbjs";
-}
-
-QVariant BinaryJsonConverter::loadFile(QIODevice *f, Converter *&outputConverter)
-{
- if (!outputConverter)
- outputConverter = &jsonConverter;
-
- QJsonDocument doc;
- if (auto file = qobject_cast<QFile *>(f)) {
- uchar *ptr = file->map(0, file->size());
- if (ptr)
- doc = QJsonDocument::fromRawData(reinterpret_cast<char *>(ptr), file->size());
- }
-
- if (doc.isNull())
- doc = QJsonDocument::fromBinaryData(f->readAll());
-
- if (!doc.isObject() && !doc.isArray()) {
- fprintf(stderr, "Failed to load Binary JSON.\n");
- exit(EXIT_FAILURE);
- }
- if (outputConverter == null)
- return QVariant();
- return doc.toVariant();
-}
-
-void BinaryJsonConverter::saveFile(QIODevice *f, const QVariant &contents, const QStringList &options)
-{
- if (!options.isEmpty()) {
- fprintf(stderr, "Unknown option '%s' to JSON output. This format has no options.\n", qPrintable(options.first()));
- exit(EXIT_FAILURE);
- }
-
- f->write(convertFromVariant(contents).toBinaryData());
-}
diff --git a/examples/corelib/serialization/convert/jsonconverter.h b/examples/corelib/serialization/convert/jsonconverter.h
index 17170603c7..445a0e6695 100644
--- a/examples/corelib/serialization/convert/jsonconverter.h
+++ b/examples/corelib/serialization/convert/jsonconverter.h
@@ -69,17 +69,4 @@ public:
void saveFile(QIODevice *f, const QVariant &contents, const QStringList &options) override;
};
-class BinaryJsonConverter : public Converter
-{
- // Converter interface
-public:
- QString name() override;
- Direction directions() override;
- Options outputOptions() override;
- const char *optionsHelp() override;
- bool probeFile(QIODevice *f) override;
- QVariant loadFile(QIODevice *f, Converter *&outputConverter) override;
- void saveFile(QIODevice *f, const QVariant &contents, const QStringList &options) override;
-};
-
#endif // JSONCONVERTER_H
diff --git a/examples/corelib/serialization/convert/xmlconverter.cpp b/examples/corelib/serialization/convert/xmlconverter.cpp
index e62801bf76..d9e724dfe1 100644
--- a/examples/corelib/serialization/convert/xmlconverter.cpp
+++ b/examples/corelib/serialization/convert/xmlconverter.cpp
@@ -336,7 +336,7 @@ static void variantToXml(QXmlStreamWriter &xml, const QVariant &v)
} else if (type == QVariant::Map || type == qMetaTypeId<VariantOrderedMap>()) {
const VariantOrderedMap map = (type == QVariant::Map) ?
VariantOrderedMap(v.toMap()) :
- v.value<VariantOrderedMap>();
+ qvariant_cast<VariantOrderedMap>(v);
xml.writeStartElement("map");
for (const auto &pair : map) {
@@ -425,10 +425,10 @@ static void variantToXml(QXmlStreamWriter &xml, const QVariant &v)
default:
if (type == qMetaTypeId<qfloat16>()) {
xml.writeAttribute(typeString, "number");
- xml.writeCharacters(QString::number(float(v.value<qfloat16>())));
+ xml.writeCharacters(QString::number(float(qvariant_cast<qfloat16>(v))));
} else if (type == qMetaTypeId<QCborSimpleType>()) {
xml.writeAttribute(typeString, "CBOR simple type");
- xml.writeCharacters(QString::number(int(v.value<QCborSimpleType>())));
+ xml.writeCharacters(QString::number(int(qvariant_cast<QCborSimpleType>(v))));
} else {
// does this convert to string?
const char *typeName = v.typeName();
diff --git a/examples/corelib/serialization/savegame/doc/src/savegame.qdoc b/examples/corelib/serialization/savegame/doc/src/savegame.qdoc
index a35f763430..e20cb6bc6c 100644
--- a/examples/corelib/serialization/savegame/doc/src/savegame.qdoc
+++ b/examples/corelib/serialization/savegame/doc/src/savegame.qdoc
@@ -37,8 +37,8 @@
game generally involves serializing each game object's member variables
to a file. Many formats can be used for this purpose, one of which is JSON.
With QJsonDocument, you also have the ability to serialize a document in a
- binary format, which is great if you don't want the save file to be
- readable, or if you need to keep the file size down.
+ \l {https://tools.ietf.org/html/rfc7049} {CBOR} format, which is great if you
+ don't want the save file to be readable, or if you need to keep the file size down.
In this example, we'll demonstrate how to save and load a simple game to
and from JSON and binary formats.
@@ -133,7 +133,7 @@
When loading a saved game in loadGame(), the first thing we do is open the
save file based on which format it was saved to; \c "save.json" for JSON,
- and \c "save.dat" for binary. We print a warning and return \c false if the
+ and \c "save.dat" for CBOR. We print a warning and return \c false if the
file couldn't be opened.
Since QJsonDocument's \l{QJsonDocument::fromJson()}{fromJson()} and
@@ -172,7 +172,7 @@
\snippet serialization/savegame/main.cpp 1
When the player has finished, we save their game. For demonstration
- purposes, we can serialize to either JSON or binary. You can examine the
+ purposes, we can serialize to either JSON or CBOR. You can examine the
contents of the files in the same directory as the executable (or re-run
the example, making sure to also specify the "load" option), although the
binary save file will contain some garbage characters (which is normal).
diff --git a/examples/corelib/serialization/savegame/game.cpp b/examples/corelib/serialization/savegame/game.cpp
index c39362bc68..58fc087b1f 100644
--- a/examples/corelib/serialization/savegame/game.cpp
+++ b/examples/corelib/serialization/savegame/game.cpp
@@ -50,6 +50,8 @@
#include "game.h"
+#include <QCborMap>
+#include <QCborValue>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
@@ -122,14 +124,14 @@ bool Game::loadGame(Game::SaveFormat saveFormat)
QJsonDocument loadDoc(saveFormat == Json
? QJsonDocument::fromJson(saveData)
- : QJsonDocument::fromBinaryData(saveData));
+ : QJsonDocument(QCborValue::fromCbor(saveData).toMap().toJsonObject()));
read(loadDoc.object());
QTextStream(stdout) << "Loaded save for "
<< loadDoc["player"]["name"].toString()
<< " using "
- << (saveFormat != Json ? "binary " : "") << "JSON...\n";
+ << (saveFormat != Json ? "CBOR" : "JSON") << "...\n";
return true;
}
//! [3]
@@ -148,10 +150,9 @@ bool Game::saveGame(Game::SaveFormat saveFormat) const
QJsonObject gameObject;
write(gameObject);
- QJsonDocument saveDoc(gameObject);
saveFile.write(saveFormat == Json
- ? saveDoc.toJson()
- : saveDoc.toBinaryData());
+ ? QJsonDocument(gameObject).toJson()
+ : QCborValue::fromJsonValue(gameObject).toCbor());
return true;
}
diff --git a/examples/corelib/threads/doc/src/mandelbrot.qdoc b/examples/corelib/threads/doc/src/mandelbrot.qdoc
index 9e3fdc1dfe..b32fa097b3 100644
--- a/examples/corelib/threads/doc/src/mandelbrot.qdoc
+++ b/examples/corelib/threads/doc/src/mandelbrot.qdoc
@@ -238,8 +238,7 @@
\snippet threads/mandelbrot/mandelbrotwidget.cpp 1
The interesting part of the constructor is the
- qRegisterMetaType() and QObject::connect() calls. Let's start
- with the \l{QObject::connect()}{connect()} call.
+ QObject::connect() call.
Although it looks like a standard signal-slot connection between
two \l{QObject}s, because the signal is emitted in a different
@@ -254,9 +253,10 @@
With queued connections, Qt must store a copy of the arguments
that were passed to the signal so that it can pass them to the
slot later on. Qt knows how to take of copy of many C++ and Qt
- types, but QImage isn't one of them. We must therefore call the
- template function qRegisterMetaType() before we can use QImage
- as a parameter in queued connections.
+ types, so, no further action is needed for QImage.
+ If a custom type was used, a call to the template function
+ qRegisterMetaType() would be required before the type
+ could be used as a parameter in queued connections.
\snippet threads/mandelbrot/mandelbrotwidget.cpp 2
\snippet threads/mandelbrot/mandelbrotwidget.cpp 3
diff --git a/examples/corelib/tools/customtype/main.cpp b/examples/corelib/tools/customtype/main.cpp
index d50bf9efea..af8e233a19 100644
--- a/examples/corelib/tools/customtype/main.cpp
+++ b/examples/corelib/tools/customtype/main.cpp
@@ -74,7 +74,7 @@ int main(int argc, char *argv[])
qDebug() << "Stored:" << stored;
//! [retrieving a custom value]
- Message retrieved = stored.value<Message>();
+ Message retrieved = qvariant_cast<Message>(stored);
qDebug() << "Retrieved:" << retrieved;
retrieved = qvariant_cast<Message>(stored);
qDebug() << "Retrieved:" << retrieved;
diff --git a/examples/embedded/flightinfo/flightinfo.cpp b/examples/embedded/flightinfo/flightinfo.cpp
index f46fc9693f..732e07583a 100644
--- a/examples/embedded/flightinfo/flightinfo.cpp
+++ b/examples/embedded/flightinfo/flightinfo.cpp
@@ -144,7 +144,7 @@ public:
private slots:
void handleNetworkData(QNetworkReply *networkReply) {
- if (!networkReply->error()) {
+ if (!networkReply->networkError()) {
if (!mapReplies.contains(networkReply)) {
// Assume UTF-8 encoded
QByteArray data = networkReply->readAll();
diff --git a/examples/embedded/lightmaps/slippymap.cpp b/examples/embedded/lightmaps/slippymap.cpp
index da003981ff..dfc21862fb 100644
--- a/examples/embedded/lightmaps/slippymap.cpp
+++ b/examples/embedded/lightmaps/slippymap.cpp
@@ -162,7 +162,7 @@ void SlippyMap::handleNetworkData(QNetworkReply *reply)
{
QImage img;
QPoint tp = reply->request().attribute(QNetworkRequest::User).toPoint();
- if (!reply->error())
+ if (!reply->networkError())
if (!img.load(reply, 0))
img = QImage();
reply->deleteLater();
diff --git a/examples/network/bearermonitor/bearermonitor.cpp b/examples/network/bearermonitor/bearermonitor.cpp
index 1a54f5ec8a..322224a902 100644
--- a/examples/network/bearermonitor/bearermonitor.cpp
+++ b/examples/network/bearermonitor/bearermonitor.cpp
@@ -80,34 +80,37 @@ BearerMonitor::BearerMonitor(QWidget *parent)
break;
}
}
- connect(&manager, SIGNAL(onlineStateChanged(bool)), this ,SLOT(onlineStateChanged(bool)));
- connect(&manager, SIGNAL(configurationAdded(const QNetworkConfiguration&)),
- this, SLOT(configurationAdded(const QNetworkConfiguration&)));
- connect(&manager, SIGNAL(configurationRemoved(const QNetworkConfiguration&)),
- this, SLOT(configurationRemoved(const QNetworkConfiguration&)));
- connect(&manager, SIGNAL(configurationChanged(const QNetworkConfiguration&)),
- this, SLOT(configurationChanged(const QNetworkConfiguration)));
- connect(&manager, SIGNAL(updateCompleted()), this, SLOT(updateConfigurations()));
+ connect(&manager, &QNetworkConfigurationManager::onlineStateChanged,
+ this, &BearerMonitor::onlineStateChanged);
+ connect(&manager, &QNetworkConfigurationManager::configurationAdded,
+ this, [this](const QNetworkConfiguration &config) { configurationAdded(config); });
+ connect(&manager, &QNetworkConfigurationManager::configurationRemoved,
+ this, &BearerMonitor::configurationRemoved);
+ connect(&manager, &QNetworkConfigurationManager::configurationChanged,
+ this, &BearerMonitor::configurationChanged);
+ connect(&manager, &QNetworkConfigurationManager::updateCompleted,
+ this, &BearerMonitor::updateConfigurations);
#if defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
- connect(registerButton, SIGNAL(clicked()), this, SLOT(registerNetwork()));
- connect(unregisterButton, SIGNAL(clicked()), this, SLOT(unregisterNetwork()));
+ connect(registerButton, &QPushButton::clicked,
+ this, &BearerMonitor::registerNetwork);
+ connect(unregisterButton, &QPushButton::clicked,
+ this, &BearerMonitor::unregisterNetwork);
#else // Q_OS_WIN && !Q_OS_WINRT
nlaGroup->hide();
#endif
- connect(treeWidget, SIGNAL(itemActivated(QTreeWidgetItem*,int)),
- this, SLOT(createSessionFor(QTreeWidgetItem*)));
+ connect(treeWidget, &QTreeWidget::itemActivated,
+ this, &BearerMonitor::createSessionFor);
+ connect(treeWidget, &QTreeWidget::currentItemChanged,
+ this, &BearerMonitor::showConfigurationFor);
- connect(treeWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
- this, SLOT(showConfigurationFor(QTreeWidgetItem*)));
-
- connect(newSessionButton, SIGNAL(clicked()),
- this, SLOT(createNewSession()));
- connect(deleteSessionButton, SIGNAL(clicked()),
- this, SLOT(deleteSession()));
- connect(scanButton, SIGNAL(clicked()),
- this, SLOT(performScan()));
+ connect(newSessionButton, &QPushButton::clicked,
+ this, &BearerMonitor::createNewSession);
+ connect(deleteSessionButton, &QPushButton::clicked,
+ this, &BearerMonitor::deleteSession);
+ connect(scanButton, &QPushButton::clicked,
+ this, &BearerMonitor::performScan);
// Just in case update all configurations so that all
// configurations are up to date.
@@ -124,7 +127,7 @@ static void updateItem(QTreeWidgetItem *item, const QNetworkConfiguration &confi
item->setData(0, Qt::UserRole, config.identifier());
QFont font = item->font(1);
- font.setBold((config.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active);
+ font.setBold(config.state().testFlag(QNetworkConfiguration::Active));
item->setFont(0, font);
}
@@ -333,8 +336,6 @@ void BearerMonitor::showConfigurationFor(QTreeWidgetItem *item)
case QNetworkConfiguration::Undefined:
configurationState->setText(tr("Undefined"));
break;
- default:
- configurationState->setText(QString());
}
switch (conf.type()) {
@@ -350,8 +351,6 @@ void BearerMonitor::showConfigurationFor(QTreeWidgetItem *item)
case QNetworkConfiguration::Invalid:
configurationType->setText(tr("Invalid"));
break;
- default:
- configurationType->setText(QString());
}
switch (conf.purpose()) {
@@ -367,8 +366,6 @@ void BearerMonitor::showConfigurationFor(QTreeWidgetItem *item)
case QNetworkConfiguration::ServiceSpecificPurpose:
configurationPurpose->setText(tr("Service Specific"));
break;
- default:
- configurationPurpose->setText(QString());
}
configurationIdentifier->setText(conf.identifier());
diff --git a/examples/network/bearermonitor/bearermonitor.h b/examples/network/bearermonitor/bearermonitor.h
index 7de186cd14..79b8d876ec 100644
--- a/examples/network/bearermonitor/bearermonitor.h
+++ b/examples/network/bearermonitor/bearermonitor.h
@@ -51,8 +51,7 @@
#ifndef BEARERMONITOR_H
#define BEARERMONITOR_H
-#include <qnetworkconfigmanager.h>
-#include <qnetworksession.h>
+#include <QNetworkConfigurationManager>
#include "ui_bearermonitor_640_480.h"
QT_USE_NAMESPACE
@@ -64,11 +63,11 @@ class BearerMonitor : public QWidget, public Ui_BearerMonitor
Q_OBJECT
public:
- BearerMonitor(QWidget *parent = 0);
+ BearerMonitor(QWidget *parent = nullptr);
~BearerMonitor();
private slots:
- void configurationAdded(const QNetworkConfiguration &config, QTreeWidgetItem *parent = 0);
+ void configurationAdded(const QNetworkConfiguration &config, QTreeWidgetItem *parent = nullptr);
void configurationRemoved(const QNetworkConfiguration &config);
void configurationChanged(const QNetworkConfiguration &config);
void updateSnapConfiguration(QTreeWidgetItem *parent, const QNetworkConfiguration &snap);
@@ -90,7 +89,7 @@ private slots:
private:
QNetworkConfigurationManager manager;
- QList<SessionWidget *> sessionWidgets;
+ QVector<SessionWidget *> sessionWidgets;
};
#endif //BEARERMONITOR_H
diff --git a/examples/network/bearermonitor/main.cpp b/examples/network/bearermonitor/main.cpp
index 363889dee4..3c2525012d 100644
--- a/examples/network/bearermonitor/main.cpp
+++ b/examples/network/bearermonitor/main.cpp
@@ -48,8 +48,8 @@
**
****************************************************************************/
-#include <QtWidgets/QApplication>
-#include <QtWidgets/QMainWindow>
+#include <QApplication>
+#include <QMainWindow>
#include "bearermonitor.h"
diff --git a/examples/network/bearermonitor/sessionwidget.cpp b/examples/network/bearermonitor/sessionwidget.cpp
index 237ceee2bd..0fd5d4f67f 100644
--- a/examples/network/bearermonitor/sessionwidget.cpp
+++ b/examples/network/bearermonitor/sessionwidget.cpp
@@ -49,10 +49,10 @@
****************************************************************************/
#include "sessionwidget.h"
-#include "qnetworkconfigmanager.h"
+#include <QNetworkConfigurationManager>
SessionWidget::SessionWidget(const QNetworkConfiguration &config, QWidget *parent)
-: QWidget(parent), statsTimer(-1)
+: QWidget(parent)
{
setupUi(this);
@@ -65,10 +65,10 @@ SessionWidget::SessionWidget(const QNetworkConfiguration &config, QWidget *paren
session = new QNetworkSession(config, this);
- connect(session, SIGNAL(stateChanged(QNetworkSession::State)),
- this, SLOT(updateSession()));
- connect(session, SIGNAL(error(QNetworkSession::SessionError)),
- this, SLOT(updateSessionError(QNetworkSession::SessionError)));
+ connect(session, &QNetworkSession::stateChanged,
+ this, &SessionWidget::updateSession);
+ connect(session, QOverload<QNetworkSession::SessionError>::of(&QNetworkSession::error),
+ this, &SessionWidget::updateSessionError);
updateSession();
@@ -76,14 +76,14 @@ SessionWidget::SessionWidget(const QNetworkConfiguration &config, QWidget *paren
configuration->setText(session->configuration().name());
- connect(openSessionButton, SIGNAL(clicked()),
- this, SLOT(openSession()));
- connect(openSyncSessionButton, SIGNAL(clicked()),
- this, SLOT(openSyncSession()));
- connect(closeSessionButton, SIGNAL(clicked()),
- this, SLOT(closeSession()));
- connect(stopSessionButton, SIGNAL(clicked()),
- this, SLOT(stopSession()));
+ connect(openSessionButton, &QPushButton::clicked,
+ this, &SessionWidget::openSession);
+ connect(openSyncSessionButton, &QPushButton::clicked,
+ this, &SessionWidget::openSyncSession);
+ connect(closeSessionButton, &QPushButton::clicked,
+ this, &SessionWidget::closeSession);
+ connect(stopSessionButton, &QPushButton::clicked,
+ this, &SessionWidget::stopSession);
}
SessionWidget::~SessionWidget()
diff --git a/examples/network/bearermonitor/sessionwidget.h b/examples/network/bearermonitor/sessionwidget.h
index ba352eefee..6b2da2c1c1 100644
--- a/examples/network/bearermonitor/sessionwidget.h
+++ b/examples/network/bearermonitor/sessionwidget.h
@@ -51,7 +51,7 @@
#ifndef SESSIONWIDGET_H
#define SESSIONWIDGET_H
-#include <qnetworksession.h>
+#include <QNetworkSession>
#include "ui_sessionwidget.h"
@@ -62,10 +62,10 @@ class SessionWidget : public QWidget, public Ui_SessionWidget
Q_OBJECT
public:
- explicit SessionWidget(const QNetworkConfiguration &config, QWidget *parent = 0);
+ explicit SessionWidget(const QNetworkConfiguration &config, QWidget *parent = nullptr);
~SessionWidget();
- void timerEvent(QTimerEvent *) override;
+ void timerEvent(QTimerEvent *e) override;
private:
void updateSessionState(QNetworkSession::State state);
@@ -80,8 +80,8 @@ private Q_SLOTS:
void updateSessionError(QNetworkSession::SessionError error);
private:
- QNetworkSession *session;
- int statsTimer;
+ QNetworkSession *session = nullptr;
+ int statsTimer = -1;
};
#endif
diff --git a/examples/network/blockingfortuneclient/blockingclient.cpp b/examples/network/blockingfortuneclient/blockingclient.cpp
index 607215cf13..5a1500d084 100644
--- a/examples/network/blockingfortuneclient/blockingclient.cpp
+++ b/examples/network/blockingfortuneclient/blockingclient.cpp
@@ -96,20 +96,21 @@ BlockingClient::BlockingClient(QWidget *parent)
buttonBox->addButton(getFortuneButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);
- connect(getFortuneButton, SIGNAL(clicked()), this, SLOT(requestNewFortune()));
- connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
-
- connect(hostLineEdit, SIGNAL(textChanged(QString)),
- this, SLOT(enableGetFortuneButton()));
- connect(portLineEdit, SIGNAL(textChanged(QString)),
- this, SLOT(enableGetFortuneButton()));
+ connect(getFortuneButton, &QPushButton::clicked,
+ this, &BlockingClient::requestNewFortune);
+ connect(quitButton, &QPushButton::clicked,
+ this, &BlockingClient::close);
+
+ connect(hostLineEdit, &QLineEdit::textChanged,
+ this, &BlockingClient::enableGetFortuneButton);
+ connect(portLineEdit, &QLineEdit::textChanged,
+ this, &BlockingClient::enableGetFortuneButton);
+//! [0]
+ connect(&thread, &FortuneThread::newFortune,
+ this, &BlockingClient::showFortune);
+ connect(&thread, &FortuneThread::error,
+ this, &BlockingClient::displayError);
//! [0]
- connect(&thread, SIGNAL(newFortune(QString)),
- this, SLOT(showFortune(QString)));
-//! [0] //! [1]
- connect(&thread, SIGNAL(error(int,QString)),
- this, SLOT(displayError(int,QString)));
-//! [1]
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addWidget(hostLabel, 0, 0);
@@ -124,30 +125,30 @@ BlockingClient::BlockingClient(QWidget *parent)
portLineEdit->setFocus();
}
-//! [2]
+//! [1]
void BlockingClient::requestNewFortune()
{
getFortuneButton->setEnabled(false);
thread.requestNewFortune(hostLineEdit->text(),
portLineEdit->text().toInt());
}
-//! [2]
+//! [1]
-//! [3]
+//! [2]
void BlockingClient::showFortune(const QString &nextFortune)
{
if (nextFortune == currentFortune) {
requestNewFortune();
return;
}
-//! [3]
+//! [2]
-//! [4]
+//! [3]
currentFortune = nextFortune;
statusLabel->setText(currentFortune);
getFortuneButton->setEnabled(true);
}
-//! [4]
+//! [3]
void BlockingClient::displayError(int socketError, const QString &message)
{
diff --git a/examples/network/blockingfortuneclient/blockingclient.h b/examples/network/blockingfortuneclient/blockingclient.h
index 2a2dd81b71..b8a7163160 100644
--- a/examples/network/blockingfortuneclient/blockingclient.h
+++ b/examples/network/blockingfortuneclient/blockingclient.h
@@ -69,7 +69,7 @@ class BlockingClient : public QWidget
Q_OBJECT
public:
- BlockingClient(QWidget *parent = 0);
+ BlockingClient(QWidget *parent = nullptr);
private slots:
void requestNewFortune();
diff --git a/examples/network/blockingfortuneclient/fortunethread.cpp b/examples/network/blockingfortuneclient/fortunethread.cpp
index 67ac7ebfa5..24801436df 100644
--- a/examples/network/blockingfortuneclient/fortunethread.cpp
+++ b/examples/network/blockingfortuneclient/fortunethread.cpp
@@ -103,7 +103,7 @@ void FortuneThread::run()
//! [6] //! [8]
if (!socket.waitForConnected(Timeout)) {
- emit error(socket.error(), socket.errorString());
+ emit error(socket.socketError(), socket.errorString());
return;
}
//! [8] //! [11]
@@ -115,7 +115,7 @@ void FortuneThread::run()
do {
if (!socket.waitForReadyRead(Timeout)) {
- emit error(socket.error(), socket.errorString());
+ emit error(socket.socketError(), socket.errorString());
return;
}
diff --git a/examples/network/blockingfortuneclient/fortunethread.h b/examples/network/blockingfortuneclient/fortunethread.h
index 0cbc3961fc..b6b63d9319 100644
--- a/examples/network/blockingfortuneclient/fortunethread.h
+++ b/examples/network/blockingfortuneclient/fortunethread.h
@@ -61,7 +61,7 @@ class FortuneThread : public QThread
Q_OBJECT
public:
- FortuneThread(QObject *parent = 0);
+ FortuneThread(QObject *parent = nullptr);
~FortuneThread();
void requestNewFortune(const QString &hostName, quint16 port);
diff --git a/examples/network/broadcastreceiver/receiver.cpp b/examples/network/broadcastreceiver/receiver.cpp
index 2f111b4795..5b932a27b9 100644
--- a/examples/network/broadcastreceiver/receiver.cpp
+++ b/examples/network/broadcastreceiver/receiver.cpp
@@ -48,8 +48,10 @@
**
****************************************************************************/
-#include <QtWidgets>
-#include <QtNetwork>
+#include <QLabel>
+#include <QPushButton>
+#include <QUdpSocket>
+#include <QVBoxLayout>
#include "receiver.h"
@@ -67,10 +69,11 @@ Receiver::Receiver(QWidget *parent)
//! [0]
//! [1]
- connect(udpSocket, SIGNAL(readyRead()),
- this, SLOT(processPendingDatagrams()));
+ connect(udpSocket, &QUdpSocket::readyRead,
+ this, &Receiver::processPendingDatagrams);
//! [1]
- connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
+ connect(quitButton, &QPushButton::clicked,
+ this, &Receiver::close);
auto buttonLayout = new QHBoxLayout;
buttonLayout->addStretch(1);
diff --git a/examples/network/dnslookup/dnslookup.cpp b/examples/network/dnslookup/dnslookup.cpp
index a2d927d43d..61f8d35a3d 100644
--- a/examples/network/dnslookup/dnslookup.cpp
+++ b/examples/network/dnslookup/dnslookup.cpp
@@ -151,9 +151,9 @@ CommandLineParseResult parseCommandLine(QCommandLineParser &parser, DnsQuery *qu
//! [0]
DnsManager::DnsManager()
+ : dns(new QDnsLookup(this))
{
- dns = new QDnsLookup(this);
- connect(dns, SIGNAL(finished()), this, SLOT(showResults()));
+ connect(dns, &QDnsLookup::finished, this, &DnsManager::showResults);
}
void DnsManager::execute()
diff --git a/examples/network/doc/src/blockingfortuneclient.qdoc b/examples/network/doc/src/blockingfortuneclient.qdoc
index ecb9a7ba62..d1c0aa79bf 100644
--- a/examples/network/doc/src/blockingfortuneclient.qdoc
+++ b/examples/network/doc/src/blockingfortuneclient.qdoc
@@ -176,21 +176,20 @@
but its implementation is slightly different:
\snippet blockingfortuneclient/blockingclient.cpp 0
- \snippet blockingfortuneclient/blockingclient.cpp 1
We connect our FortuneThread's two signals newFortune() and error() (which
are somewhat similar to QTcpSocket::readyRead() and QTcpSocket::error() in
the previous example) to requestNewFortune() and displayError().
- \snippet blockingfortuneclient/blockingclient.cpp 2
+ \snippet blockingfortuneclient/blockingclient.cpp 1
The requestNewFortune() slot calls FortuneThread::requestNewFortune(),
which \e shedules the request. When the thread has received a new fortune
and emits newFortune(), our showFortune() slot is called:
- \snippet blockingfortuneclient/blockingclient.cpp 3
+ \snippet blockingfortuneclient/blockingclient.cpp 2
\codeline
- \snippet blockingfortuneclient/blockingclient.cpp 4
+ \snippet blockingfortuneclient/blockingclient.cpp 3
Here, we simply display the fortune we received as the argument.
diff --git a/examples/network/download/main.cpp b/examples/network/download/main.cpp
index 96111983ea..f496c1723e 100644
--- a/examples/network/download/main.cpp
+++ b/examples/network/download/main.cpp
@@ -80,8 +80,8 @@ public slots:
DownloadManager::DownloadManager()
{
- connect(&manager, SIGNAL(finished(QNetworkReply*)),
- SLOT(downloadFinished(QNetworkReply*)));
+ connect(&manager, &QNetworkAccessManager::finished,
+ this, &DownloadManager::downloadFinished);
}
void DownloadManager::doDownload(const QUrl &url)
@@ -90,8 +90,8 @@ void DownloadManager::doDownload(const QUrl &url)
QNetworkReply *reply = manager.get(request);
#if QT_CONFIG(ssl)
- connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
- SLOT(sslErrors(QList<QSslError>)));
+ connect(reply, &QNetworkReply::sslErrors,
+ this, &DownloadManager::sslErrors);
#endif
currentDownloads.append(reply);
@@ -175,7 +175,7 @@ void DownloadManager::sslErrors(const QList<QSslError> &sslErrors)
void DownloadManager::downloadFinished(QNetworkReply *reply)
{
QUrl url = reply->url();
- if (reply->error()) {
+ if (reply->networkError()) {
fprintf(stderr, "Download of %s failed: %s\n",
url.toEncoded().constData(),
qPrintable(reply->errorString()));
diff --git a/examples/network/downloadmanager/downloadmanager.cpp b/examples/network/downloadmanager/downloadmanager.cpp
index 9e0c03c6af..eceb48977b 100644
--- a/examples/network/downloadmanager/downloadmanager.cpp
+++ b/examples/network/downloadmanager/downloadmanager.cpp
@@ -67,13 +67,13 @@ void DownloadManager::append(const QStringList &urls)
append(QUrl::fromEncoded(urlAsString.toLocal8Bit()));
if (downloadQueue.isEmpty())
- QTimer::singleShot(0, this, SIGNAL(finished()));
+ QTimer::singleShot(0, this, &DownloadManager::finished);
}
void DownloadManager::append(const QUrl &url)
{
if (downloadQueue.isEmpty())
- QTimer::singleShot(0, this, SLOT(startNextDownload()));
+ QTimer::singleShot(0, this, &DownloadManager::startNextDownload);
downloadQueue.enqueue(url);
++totalCount;
@@ -123,12 +123,12 @@ void DownloadManager::startNextDownload()
QNetworkRequest request(url);
currentDownload = manager.get(request);
- connect(currentDownload, SIGNAL(downloadProgress(qint64,qint64)),
- SLOT(downloadProgress(qint64,qint64)));
- connect(currentDownload, SIGNAL(finished()),
- SLOT(downloadFinished()));
- connect(currentDownload, SIGNAL(readyRead()),
- SLOT(downloadReadyRead()));
+ connect(currentDownload, &QNetworkReply::downloadProgress,
+ this, &DownloadManager::downloadProgress);
+ connect(currentDownload, &QNetworkReply::finished,
+ this, &DownloadManager::downloadFinished);
+ connect(currentDownload, &QNetworkReply::readyRead,
+ this, &DownloadManager::downloadReadyRead);
// prepare the output
printf("Downloading %s...\n", url.toEncoded().constData());
@@ -162,7 +162,7 @@ void DownloadManager::downloadFinished()
progressBar.clear();
output.close();
- if (currentDownload->error()) {
+ if (currentDownload->networkError()) {
// download failed
fprintf(stderr, "Failed: %s\n", qPrintable(currentDownload->errorString()));
output.remove();
diff --git a/examples/network/downloadmanager/main.cpp b/examples/network/downloadmanager/main.cpp
index e3ba490992..eb1bd1ce9a 100644
--- a/examples/network/downloadmanager/main.cpp
+++ b/examples/network/downloadmanager/main.cpp
@@ -76,6 +76,7 @@ int main(int argc, char **argv)
DownloadManager manager;
manager.append(arguments);
- QObject::connect(&manager, SIGNAL(finished()), &app, SLOT(quit()));
+ QObject::connect(&manager, &DownloadManager::finished,
+ &app, &QCoreApplication::quit);
app.exec();
}
diff --git a/examples/network/googlesuggest/googlesuggest.cpp b/examples/network/googlesuggest/googlesuggest.cpp
index d27beafd1e..1ae515f530 100644
--- a/examples/network/googlesuggest/googlesuggest.cpp
+++ b/examples/network/googlesuggest/googlesuggest.cpp
@@ -48,9 +48,9 @@
**
****************************************************************************/
-//! [1]
#include "googlesuggest.h"
+//! [1]
const QString gsuggestUrl(QStringLiteral("http://google.com/complete/search?output=toolbar&q=%1"));
//! [1]
@@ -74,16 +74,18 @@ GSuggestCompletion::GSuggestCompletion(QLineEdit *parent): QObject(parent), edit
popup->installEventFilter(this);
- connect(popup, SIGNAL(itemClicked(QTreeWidgetItem*,int)),
- SLOT(doneCompletion()));
+ connect(popup, &QTreeWidget::itemClicked,
+ this, &GSuggestCompletion::doneCompletion);
timer.setSingleShot(true);
timer.setInterval(500);
- connect(&timer, SIGNAL(timeout()), SLOT(autoSuggest()));
- connect(editor, SIGNAL(textEdited(QString)), &timer, SLOT(start()));
+ connect(&timer, &QTimer::timeout,
+ this, &GSuggestCompletion::autoSuggest);
+ connect(editor, &QLineEdit::textEdited,
+ &timer, QOverload<>::of(&QTimer::start));
- connect(&networkManager, SIGNAL(finished(QNetworkReply*)),
- this, SLOT(handleNetworkData(QNetworkReply*)));
+ connect(&networkManager, &QNetworkAccessManager::finished,
+ this, &GSuggestCompletion::handleNetworkData);
}
//! [2]
@@ -207,7 +209,7 @@ void GSuggestCompletion::preventSuggest()
void GSuggestCompletion::handleNetworkData(QNetworkReply *networkReply)
{
QUrl url = networkReply->url();
- if (networkReply->error() == QNetworkReply::NoError) {
+ if (networkReply->networkError() == QNetworkReply::NoError) {
QVector<QString> choices;
QByteArray response(networkReply->readAll());
diff --git a/examples/network/googlesuggest/searchbox.cpp b/examples/network/googlesuggest/searchbox.cpp
index d0bdb70daa..9057c1ccdf 100644
--- a/examples/network/googlesuggest/searchbox.cpp
+++ b/examples/network/googlesuggest/searchbox.cpp
@@ -57,11 +57,11 @@
const QString gsearchUrl = QStringLiteral("http://www.google.com/search?q=%1");
//! [1]
-SearchBox::SearchBox(QWidget *parent): QLineEdit(parent)
+SearchBox::SearchBox(QWidget *parent)
+ : QLineEdit(parent)
+ , completer(new GSuggestCompletion(this))
{
- completer = new GSuggestCompletion(this);
-
- connect(this, SIGNAL(returnPressed()),this, SLOT(doSearch()));
+ connect(this, &SearchBox::returnPressed, this, &SearchBox::doSearch);
setWindowTitle("Search with Google");
diff --git a/examples/network/http/httpwindow.cpp b/examples/network/http/httpwindow.cpp
index c7bf0c0dff..d0eb2529cd 100644
--- a/examples/network/http/httpwindow.cpp
+++ b/examples/network/http/httpwindow.cpp
@@ -249,7 +249,7 @@ void HttpWindow::httpFinished()
return;
}
- if (reply->error()) {
+ if (reply->networkError()) {
QFile::remove(fi.absoluteFilePath());
statusLabel->setText(tr("Download failed:\n%1.").arg(reply->errorString()));
downloadButton->setEnabled(true);
diff --git a/examples/network/multicastreceiver/receiver.cpp b/examples/network/multicastreceiver/receiver.cpp
index d793242ad0..3737d64f96 100644
--- a/examples/network/multicastreceiver/receiver.cpp
+++ b/examples/network/multicastreceiver/receiver.cpp
@@ -80,10 +80,12 @@ Receiver::Receiver(QWidget *parent)
!udpSocket6.joinMulticastGroup(groupAddress6))
statusLabel->setText(tr("Listening for multicast messages on IPv4 only"));
- connect(&udpSocket4, SIGNAL(readyRead()),
- this, SLOT(processPendingDatagrams()));
- connect(&udpSocket6, &QUdpSocket::readyRead, this, &Receiver::processPendingDatagrams);
- connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
+ connect(&udpSocket4, &QUdpSocket::readyRead,
+ this, &Receiver::processPendingDatagrams);
+ connect(&udpSocket6, &QUdpSocket::readyRead,
+ this, &Receiver::processPendingDatagrams);
+ connect(quitButton, &QPushButton::clicked,
+ this, &Receiver::close);
}
void Receiver::processPendingDatagrams()
diff --git a/examples/network/multistreamclient/client.cpp b/examples/network/multistreamclient/client.cpp
index 112fb2e1a0..db6e3ba304 100644
--- a/examples/network/multistreamclient/client.cpp
+++ b/examples/network/multistreamclient/client.cpp
@@ -126,8 +126,8 @@ Client::Client(QWidget *parent)
connect(sctpSocket, &QSctpSocket::connected, this, &Client::connected);
connect(sctpSocket, &QSctpSocket::disconnected, this, &Client::disconnected);
connect(sctpSocket, &QSctpSocket::channelReadyRead, this, &Client::readDatagram);
- connect(sctpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
- this, SLOT(displayError(QAbstractSocket::SocketError)));
+ connect(sctpSocket, QOverload<QAbstractSocket::SocketError>::of(&QSctpSocket::error),
+ this, &Client::displayError);
connect(consumers[SctpChannels::Time], &Consumer::writeDatagram, this, &Client::writeDatagram);
connect(consumers[SctpChannels::Chat], &Consumer::writeDatagram, this, &Client::writeDatagram);
diff --git a/examples/network/network-chat/chatdialog.cpp b/examples/network/network-chat/chatdialog.cpp
index 615df3a318..ce6e39a8fc 100644
--- a/examples/network/network-chat/chatdialog.cpp
+++ b/examples/network/network-chat/chatdialog.cpp
@@ -62,14 +62,14 @@ ChatDialog::ChatDialog(QWidget *parent)
textEdit->setReadOnly(true);
listWidget->setFocusPolicy(Qt::NoFocus);
- connect(lineEdit, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
- connect(lineEdit, SIGNAL(returnPressed()), this, SLOT(returnPressed()));
- connect(&client, SIGNAL(newMessage(QString,QString)),
- this, SLOT(appendMessage(QString,QString)));
- connect(&client, SIGNAL(newParticipant(QString)),
- this, SLOT(newParticipant(QString)));
- connect(&client, SIGNAL(participantLeft(QString)),
- this, SLOT(participantLeft(QString)));
+ connect(lineEdit, &QLineEdit::returnPressed,
+ this, &ChatDialog::returnPressed);
+ connect(&client, &Client::newMessage,
+ this, &ChatDialog::appendMessage);
+ connect(&client, &Client::newParticipant,
+ this, &ChatDialog::newParticipant);
+ connect(&client, &Client::participantLeft,
+ this, &ChatDialog::participantLeft);
myNickName = client.nickName();
newParticipant(myNickName);
diff --git a/examples/network/network-chat/chatdialog.h b/examples/network/network-chat/chatdialog.h
index c65861c6e6..27ae0ca72a 100644
--- a/examples/network/network-chat/chatdialog.h
+++ b/examples/network/network-chat/chatdialog.h
@@ -59,7 +59,7 @@ class ChatDialog : public QDialog, private Ui::ChatDialog
Q_OBJECT
public:
- ChatDialog(QWidget *parent = 0);
+ ChatDialog(QWidget *parent = nullptr);
public slots:
void appendMessage(const QString &from, const QString &message);
diff --git a/examples/network/network-chat/client.cpp b/examples/network/network-chat/client.cpp
index b76ef18238..d451181813 100644
--- a/examples/network/network-chat/client.cpp
+++ b/examples/network/network-chat/client.cpp
@@ -60,10 +60,10 @@ Client::Client()
peerManager->setServerPort(server.serverPort());
peerManager->startBroadcasting();
- QObject::connect(peerManager, SIGNAL(newConnection(Connection*)),
- this, SLOT(newConnection(Connection*)));
- QObject::connect(&server, SIGNAL(newConnection(Connection*)),
- this, SLOT(newConnection(Connection*)));
+ connect(peerManager, &PeerManager::newConnection,
+ this, &Client::newConnection);
+ connect(&server, &Server::newConnection,
+ this, &Client::newConnection);
}
void Client::sendMessage(const QString &message)
@@ -102,10 +102,10 @@ void Client::newConnection(Connection *connection)
{
connection->setGreetingMessage(peerManager->userName());
- connect(connection, SIGNAL(error(QAbstractSocket::SocketError)),
- this, SLOT(connectionError(QAbstractSocket::SocketError)));
- connect(connection, SIGNAL(disconnected()), this, SLOT(disconnected()));
- connect(connection, SIGNAL(readyForUse()), this, SLOT(readyForUse()));
+ connect(connection, QOverload<QAbstractSocket::SocketError>::of(&Connection::error),
+ this, &Client::connectionError);
+ connect(connection, &Connection::disconnected, this, &Client::disconnected);
+ connect(connection, &Connection::readyForUse, this, &Client::readyForUse);
}
void Client::readyForUse()
@@ -115,8 +115,8 @@ void Client::readyForUse()
connection->peerPort()))
return;
- connect(connection, SIGNAL(newMessage(QString,QString)),
- this, SIGNAL(newMessage(QString,QString)));
+ connect(connection, &Connection::newMessage,
+ this, &Client::newMessage);
peers.insert(connection->peerAddress(), connection);
QString nick = connection->name();
diff --git a/examples/network/network-chat/connection.cpp b/examples/network/network-chat/connection.cpp
index 58cf67eb6d..cffd495349 100644
--- a/examples/network/network-chat/connection.cpp
+++ b/examples/network/network-chat/connection.cpp
@@ -82,11 +82,14 @@ Connection::Connection(QObject *parent)
isGreetingMessageSent = false;
pingTimer.setInterval(PingInterval);
- QObject::connect(this, SIGNAL(readyRead()), this, SLOT(processReadyRead()));
- QObject::connect(this, SIGNAL(disconnected()), &pingTimer, SLOT(stop()));
- QObject::connect(&pingTimer, SIGNAL(timeout()), this, SLOT(sendPing()));
- QObject::connect(this, SIGNAL(connected()),
- this, SLOT(sendGreetingMessage()));
+ connect(this, &QTcpSocket::readyRead, this,
+ &Connection::processReadyRead);
+ connect(this, &QTcpSocket::disconnected,
+ &pingTimer, &QTimer::stop);
+ connect(&pingTimer, &QTimer::timeout,
+ this, &Connection::sendPing);
+ connect(this, &QTcpSocket::connected,
+ this, &Connection::sendGreetingMessage);
}
Connection::Connection(qintptr socketDescriptor, QObject *parent)
diff --git a/examples/network/network-chat/connection.h b/examples/network/network-chat/connection.h
index fa0671a522..e6f36f7cd9 100644
--- a/examples/network/network-chat/connection.h
+++ b/examples/network/network-chat/connection.h
@@ -79,8 +79,8 @@ public:
Undefined
};
- Connection(QObject *parent = 0);
- Connection(qintptr socketDescriptor, QObject *parent = 0);
+ Connection(QObject *parent = nullptr);
+ Connection(qintptr socketDescriptor, QObject *parent = nullptr);
~Connection();
QString name() const;
diff --git a/examples/network/network-chat/peermanager.cpp b/examples/network/network-chat/peermanager.cpp
index 5c48edb1b9..2c9d182211 100644
--- a/examples/network/network-chat/peermanager.cpp
+++ b/examples/network/network-chat/peermanager.cpp
@@ -81,12 +81,12 @@ PeerManager::PeerManager(Client *client)
broadcastSocket.bind(QHostAddress::Any, broadcastPort, QUdpSocket::ShareAddress
| QUdpSocket::ReuseAddressHint);
- connect(&broadcastSocket, SIGNAL(readyRead()),
- this, SLOT(readBroadcastDatagram()));
+ connect(&broadcastSocket, &QUdpSocket::readyRead,
+ this, &PeerManager::readBroadcastDatagram);
broadcastTimer.setInterval(BroadcastInterval);
- connect(&broadcastTimer, SIGNAL(timeout()),
- this, SLOT(sendBroadcastDatagram()));
+ connect(&broadcastTimer, &QTimer::timeout,
+ this, &PeerManager::sendBroadcastDatagram);
}
void PeerManager::setServerPort(int port)
diff --git a/examples/network/network-chat/server.h b/examples/network/network-chat/server.h
index d86ed36bce..0a7e6e18c1 100644
--- a/examples/network/network-chat/server.h
+++ b/examples/network/network-chat/server.h
@@ -60,7 +60,7 @@ class Server : public QTcpServer
Q_OBJECT
public:
- Server(QObject *parent = 0);
+ Server(QObject *parent = nullptr);
signals:
void newConnection(Connection *connection);
diff --git a/examples/network/network.pro b/examples/network/network.pro
index 1556e26ab1..af3c0df43e 100644
--- a/examples/network/network.pro
+++ b/examples/network/network.pro
@@ -29,7 +29,7 @@ qtHaveModule(widgets) {
}
- qtConfig(openssl): SUBDIRS += securesocketclient
+ qtConfig(ssl): SUBDIRS += securesocketclient
qtConfig(dtls): SUBDIRS += secureudpserver secureudpclient
qtConfig(sctp): SUBDIRS += multistreamserver multistreamclient
}
diff --git a/examples/network/securesocketclient/main.cpp b/examples/network/securesocketclient/main.cpp
index e9c413577f..7cda94cc34 100644
--- a/examples/network/securesocketclient/main.cpp
+++ b/examples/network/securesocketclient/main.cpp
@@ -63,8 +63,8 @@ int main(int argc, char **argv)
QApplication app(argc, argv);
if (!QSslSocket::supportsSsl()) {
- QMessageBox::information(0, "Secure Socket Client",
- "This system does not support SSL/TLS.");
+ QMessageBox::information(nullptr, "Secure Socket Client",
+ "This system does not support TLS.");
return -1;
}
diff --git a/examples/network/securesocketclient/sslclient.cpp b/examples/network/securesocketclient/sslclient.cpp
index 79ed7746d6..6eb1075996 100644
--- a/examples/network/securesocketclient/sslclient.cpp
+++ b/examples/network/securesocketclient/sslclient.cpp
@@ -54,8 +54,6 @@
#include "ui_sslclient.h"
#include "ui_sslerrors.h"
-#include <QtCore>
-
SslClient::SslClient(QWidget *parent)
: QWidget(parent)
{
@@ -185,16 +183,17 @@ void SslClient::setupUi()
form->hostNameEdit->setSelection(0, form->hostNameEdit->text().size());
form->sessionOutput->setHtml(tr("&lt;not connected&gt;"));
- connect(form->hostNameEdit, SIGNAL(textChanged(QString)),
- this, SLOT(updateEnabledState()));
- connect(form->connectButton, SIGNAL(clicked()),
- this, SLOT(secureConnect()));
- connect(form->sendButton, SIGNAL(clicked()),
- this, SLOT(sendData()));
+ connect(form->hostNameEdit, &QLineEdit::textChanged,
+ this, &SslClient::updateEnabledState);
+ connect(form->connectButton, &QPushButton::clicked,
+ this, &SslClient::secureConnect);
+ connect(form->sendButton, &QPushButton::clicked,
+ this, &SslClient::sendData);
padLock = new QToolButton;
padLock->setIcon(QIcon(":/encrypted.png"));
- connect(padLock, SIGNAL(clicked()), this, SLOT(displayCertificateInfo()));
+ connect(padLock, &QToolButton::clicked,
+ this, &SslClient::displayCertificateInfo);
#if QT_CONFIG(cursor)
padLock->setCursor(Qt::ArrowCursor);
@@ -223,16 +222,16 @@ void SslClient::setupSecureSocket()
socket = new QSslSocket(this);
- connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
- this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
- connect(socket, SIGNAL(encrypted()),
- this, SLOT(socketEncrypted()));
- connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
- this, SLOT(socketError(QAbstractSocket::SocketError)));
- connect(socket, SIGNAL(sslErrors(QList<QSslError>)),
- this, SLOT(sslErrors(QList<QSslError>)));
- connect(socket, SIGNAL(readyRead()),
- this, SLOT(socketReadyRead()));
+ connect(socket, &QSslSocket::stateChanged,
+ this, &SslClient::socketStateChanged);
+ connect(socket, &QSslSocket::encrypted,
+ this, &SslClient::socketEncrypted);
+ connect(socket, QOverload<QAbstractSocket::SocketError>::of(&QSslSocket::error),
+ this, &SslClient::socketError);
+ connect(socket, QOverload<const QList<QSslError> &>::of(&QSslSocket::sslErrors),
+ this, &SslClient::sslErrors);
+ connect(socket, &QSslSocket::readyRead,
+ this, &SslClient::socketReadyRead);
}
diff --git a/examples/network/threadedfortuneserver/dialog.cpp b/examples/network/threadedfortuneserver/dialog.cpp
index fcd6655ab9..e5b389f1e6 100644
--- a/examples/network/threadedfortuneserver/dialog.cpp
+++ b/examples/network/threadedfortuneserver/dialog.cpp
@@ -89,7 +89,7 @@ Dialog::Dialog(QWidget *parent)
"Run the Fortune Client example now.")
.arg(ipAddress).arg(server.serverPort()));
- connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
+ connect(quitButton, &QPushButton::clicked, this, &Dialog::close);
QHBoxLayout *buttonLayout = new QHBoxLayout;
buttonLayout->addStretch(1);
diff --git a/examples/network/threadedfortuneserver/dialog.h b/examples/network/threadedfortuneserver/dialog.h
index d127b8bfc2..2898c5311c 100644
--- a/examples/network/threadedfortuneserver/dialog.h
+++ b/examples/network/threadedfortuneserver/dialog.h
@@ -64,7 +64,7 @@ class Dialog : public QWidget
Q_OBJECT
public:
- Dialog(QWidget *parent = 0);
+ Dialog(QWidget *parent = nullptr);
private:
QLabel *statusLabel;
diff --git a/examples/network/threadedfortuneserver/fortuneserver.cpp b/examples/network/threadedfortuneserver/fortuneserver.cpp
index 791ffc71f4..73d7e22531 100644
--- a/examples/network/threadedfortuneserver/fortuneserver.cpp
+++ b/examples/network/threadedfortuneserver/fortuneserver.cpp
@@ -74,7 +74,7 @@ void FortuneServer::incomingConnection(qintptr socketDescriptor)
{
QString fortune = fortunes.at(QRandomGenerator::global()->bounded(fortunes.size()));
FortuneThread *thread = new FortuneThread(socketDescriptor, fortune, this);
- connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
+ connect(thread, &FortuneThread::finished, thread, &FortuneThread::deleteLater);
thread->start();
}
//! [1]
diff --git a/examples/network/threadedfortuneserver/fortuneserver.h b/examples/network/threadedfortuneserver/fortuneserver.h
index dc0949bcb2..26ea3d1cbb 100644
--- a/examples/network/threadedfortuneserver/fortuneserver.h
+++ b/examples/network/threadedfortuneserver/fortuneserver.h
@@ -60,7 +60,7 @@ class FortuneServer : public QTcpServer
Q_OBJECT
public:
- FortuneServer(QObject *parent = 0);
+ FortuneServer(QObject *parent = nullptr);
protected:
void incomingConnection(qintptr socketDescriptor) override;
diff --git a/examples/network/threadedfortuneserver/fortunethread.cpp b/examples/network/threadedfortuneserver/fortunethread.cpp
index ddde5121a3..2e730c6c8f 100644
--- a/examples/network/threadedfortuneserver/fortunethread.cpp
+++ b/examples/network/threadedfortuneserver/fortunethread.cpp
@@ -65,7 +65,7 @@ void FortuneThread::run()
QTcpSocket tcpSocket;
//! [1] //! [2]
if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
- emit error(tcpSocket.error());
+ emit error(tcpSocket.socketError());
return;
}
//! [2] //! [3]
diff --git a/examples/network/torrent/addtorrentdialog.cpp b/examples/network/torrent/addtorrentdialog.cpp
index c87110ac4a..129ad8c968 100644
--- a/examples/network/torrent/addtorrentdialog.cpp
+++ b/examples/network/torrent/addtorrentdialog.cpp
@@ -73,12 +73,12 @@ AddTorrentDialog::AddTorrentDialog(QWidget *parent)
{
ui.setupUi(this);
- connect(ui.browseTorrents, SIGNAL(clicked()),
- this, SLOT(selectTorrent()));
- connect(ui.browseDestination, SIGNAL(clicked()),
- this, SLOT(selectDestination()));
- connect(ui.torrentFile, SIGNAL(textChanged(QString)),
- this, SLOT(setTorrent(QString)));
+ connect(ui.browseTorrents, &QPushButton::clicked,
+ this, &AddTorrentDialog::selectTorrent);
+ connect(ui.browseDestination, &QPushButton::clicked,
+ this, &AddTorrentDialog::selectDestination);
+ connect(ui.torrentFile, &QLineEdit::textChanged,
+ this, &AddTorrentDialog::setTorrent);
ui.destinationFolder->setText(destinationDirectory = QDir::current().path());
ui.torrentFile->setFocus();
diff --git a/examples/network/torrent/addtorrentdialog.h b/examples/network/torrent/addtorrentdialog.h
index b5bd1df84f..00546c624c 100644
--- a/examples/network/torrent/addtorrentdialog.h
+++ b/examples/network/torrent/addtorrentdialog.h
@@ -60,7 +60,7 @@ class AddTorrentDialog : public QDialog
Q_OBJECT
public:
- AddTorrentDialog(QWidget *parent = 0);
+ AddTorrentDialog(QWidget *parent = nullptr);
QString torrentFileName() const;
QString destinationFolder() const;
diff --git a/examples/network/torrent/filemanager.h b/examples/network/torrent/filemanager.h
index 82f9983ea6..1438ed5404 100644
--- a/examples/network/torrent/filemanager.h
+++ b/examples/network/torrent/filemanager.h
@@ -70,7 +70,7 @@ class FileManager : public QThread
Q_OBJECT
public:
- FileManager(QObject *parent = 0);
+ FileManager(QObject *parent = nullptr);
virtual ~FileManager();
inline void setMetaInfo(const MetaInfo &info) { metaInfo = info; }
diff --git a/examples/network/torrent/mainwindow.cpp b/examples/network/torrent/mainwindow.cpp
index 704012ef6d..331fa12944 100644
--- a/examples/network/torrent/mainwindow.cpp
+++ b/examples/network/torrent/mainwindow.cpp
@@ -60,7 +60,7 @@ class TorrentView : public QTreeWidget
{
Q_OBJECT
public:
- TorrentView(QWidget *parent = 0);
+ TorrentView(QWidget *parent = nullptr);
#if QT_CONFIG(draganddrop)
signals:
@@ -110,7 +110,7 @@ public:
};
MainWindow::MainWindow(QWidget *parent)
- : QMainWindow(parent), quitDialog(0), saveChanges(false)
+ : QMainWindow(parent), quitDialog(nullptr), saveChanges(false)
{
// Initialize some static strings
QStringList headers;
@@ -147,12 +147,12 @@ MainWindow::MainWindow(QWidget *parent)
fileMenu->addAction(pauseTorrentAction);
fileMenu->addAction(removeTorrentAction);
fileMenu->addSeparator();
- fileMenu->addAction(QIcon(":/icons/exit.png"), tr("E&xit"), this, SLOT(close()));
+ fileMenu->addAction(QIcon(":/icons/exit.png"), tr("E&xit"), this, &MainWindow::close);
// Help menu
QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
- helpMenu->addAction(tr("&About"), this, SLOT(about()));
- helpMenu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt()));
+ helpMenu->addAction(tr("&About"), this, &MainWindow::about);
+ helpMenu->addAction(tr("About &Qt"), qApp, QApplication::aboutQt);
// Top toolbar
QToolBar *topBar = new QToolBar(tr("Tools"));
@@ -188,24 +188,24 @@ MainWindow::MainWindow(QWidget *parent)
#endif
// Set up connections
- connect(torrentView, SIGNAL(itemSelectionChanged()),
- this, SLOT(setActionsEnabled()));
- connect(torrentView, SIGNAL(fileDropped(QString)),
- this, SLOT(acceptFileDrop(QString)));
- connect(uploadLimitSlider, SIGNAL(valueChanged(int)),
- this, SLOT(setUploadLimit(int)));
- connect(downloadLimitSlider, SIGNAL(valueChanged(int)),
- this, SLOT(setDownloadLimit(int)));
- connect(newTorrentAction, SIGNAL(triggered()),
- this, SLOT(addTorrent()));
- connect(pauseTorrentAction, SIGNAL(triggered()),
- this, SLOT(pauseTorrent()));
- connect(removeTorrentAction, SIGNAL(triggered()),
- this, SLOT(removeTorrent()));
- connect(upActionTool, SIGNAL(triggered(bool)),
- this, SLOT(moveTorrentUp()));
- connect(downActionTool, SIGNAL(triggered(bool)),
- this, SLOT(moveTorrentDown()));
+ connect(torrentView, &TorrentView::itemSelectionChanged,
+ this, &MainWindow::setActionsEnabled);
+ connect(torrentView, &TorrentView::fileDropped,
+ this, &MainWindow::acceptFileDrop);
+ connect(uploadLimitSlider, &QSlider::valueChanged,
+ this, &MainWindow::setUploadLimit);
+ connect(downloadLimitSlider, &QSlider::valueChanged,
+ this, &MainWindow::setDownloadLimit);
+ connect(newTorrentAction, &QAction::triggered,
+ this, QOverload<>::of(&MainWindow::addTorrent));
+ connect(pauseTorrentAction, &QAction::triggered,
+ this, &MainWindow::pauseTorrent);
+ connect(removeTorrentAction, &QAction::triggered,
+ this, &MainWindow::removeTorrent);
+ connect(upActionTool, &QAction::triggered,
+ this, &MainWindow::moveTorrentUp);
+ connect(downActionTool, &QAction::triggered,
+ this, &MainWindow::moveTorrentDown);
// Load settings and start
setWindowTitle(tr("Torrent Client"));
@@ -297,7 +297,7 @@ bool MainWindow::addTorrent()
addTorrent(fileName, addTorrentDialog->destinationFolder());
if (!saveChanges) {
saveChanges = true;
- QTimer::singleShot(1000, this, SLOT(saveSettings()));
+ QTimer::singleShot(1000, this, &MainWindow::saveSettings);
}
return true;
}
@@ -311,7 +311,8 @@ void MainWindow::removeTorrent()
// Stop the client.
client->disconnect();
- connect(client, SIGNAL(stopped()), this, SLOT(torrentStopped()));
+ connect(client, &TorrentClient::stopped,
+ this, &MainWindow::torrentStopped);
client->stop();
// Remove the row from the view.
@@ -379,13 +380,20 @@ bool MainWindow::addTorrent(const QString &fileName, const QString &destinationF
client->setDumpedState(resumeState);
// Setup the client connections.
- connect(client, SIGNAL(stateChanged(TorrentClient::State)), this, SLOT(updateState(TorrentClient::State)));
- connect(client, SIGNAL(peerInfoUpdated()), this, SLOT(updatePeerInfo()));
- connect(client, SIGNAL(progressUpdated(int)), this, SLOT(updateProgress(int)));
- connect(client, SIGNAL(downloadRateUpdated(int)), this, SLOT(updateDownloadRate(int)));
- connect(client, SIGNAL(uploadRateUpdated(int)), this, SLOT(updateUploadRate(int)));
- connect(client, SIGNAL(stopped()), this, SLOT(torrentStopped()));
- connect(client, SIGNAL(error(TorrentClient::Error)), this, SLOT(torrentError(TorrentClient::Error)));
+ connect(client, &TorrentClient::stateChanged,
+ this, &MainWindow::updateState);
+ connect(client, &TorrentClient::peerInfoUpdated,
+ this, &MainWindow::updatePeerInfo);
+ connect(client, &TorrentClient::progressUpdated,
+ this, &MainWindow::updateProgress);
+ connect(client, &TorrentClient::downloadRateUpdated,
+ this, &MainWindow::updateDownloadRate);
+ connect(client, &TorrentClient::uploadRateUpdated,
+ this, &MainWindow::updateUploadRate);
+ connect(client, &TorrentClient::stopped,
+ this, &MainWindow::torrentStopped);
+ connect(client, QOverload<TorrentClient::Error>::of(&TorrentClient::error),
+ this, &MainWindow::torrentError);
// Add the client to the list of downloading jobs.
Job job;
@@ -414,7 +422,7 @@ bool MainWindow::addTorrent(const QString &fileName, const QString &destinationF
if (!saveChanges) {
saveChanges = true;
- QTimer::singleShot(5000, this, SLOT(saveSettings()));
+ QTimer::singleShot(5000, this, &MainWindow::saveSettings);
}
client->start();
return true;
@@ -491,15 +499,15 @@ void MainWindow::setActionsEnabled()
{
// Find the view item and client for the current row, and update
// the states of the actions.
- QTreeWidgetItem *item = 0;
+ QTreeWidgetItem *item = nullptr;
if (!torrentView->selectedItems().isEmpty())
item = torrentView->selectedItems().first();
- TorrentClient *client = item ? jobs.at(torrentView->indexOfTopLevelItem(item)).client : 0;
+ TorrentClient *client = item ? jobs.at(torrentView->indexOfTopLevelItem(item)).client : nullptr;
bool pauseEnabled = client && ((client->state() == TorrentClient::Paused)
|| (client->state() > TorrentClient::Preparing));
- removeTorrentAction->setEnabled(item != 0);
- pauseTorrentAction->setEnabled(item != 0 && pauseEnabled);
+ removeTorrentAction->setEnabled(item != nullptr);
+ pauseTorrentAction->setEnabled(item && pauseEnabled);
if (client && client->state() == TorrentClient::Paused) {
pauseTorrentAction->setIcon(QIcon(":/icons/player_play.png"));
@@ -524,7 +532,7 @@ void MainWindow::updateDownloadRate(int bytesPerSecond)
if (!saveChanges) {
saveChanges = true;
- QTimer::singleShot(5000, this, SLOT(saveSettings()));
+ QTimer::singleShot(5000, this, &MainWindow::saveSettings);
}
}
@@ -538,7 +546,7 @@ void MainWindow::updateUploadRate(int bytesPerSecond)
if (!saveChanges) {
saveChanges = true;
- QTimer::singleShot(5000, this, SLOT(saveSettings()));
+ QTimer::singleShot(5000, this, &MainWindow::saveSettings);
}
}
@@ -649,7 +657,7 @@ void MainWindow::about()
about.setWindowTitle(tr("About Torrent Client"));
about.setLayout(mainLayout);
- connect(quitButton, SIGNAL(clicked()), &about, SLOT(close()));
+ connect(quitButton, &QPushButton::clicked, &about, &QDialog::close);
about.exec();
}
@@ -688,7 +696,7 @@ void MainWindow::closeEvent(QCloseEvent *)
++jobsToStop;
TorrentClient *client = job.client;
client->disconnect();
- connect(client, SIGNAL(stopped()), this, SLOT(torrentStopped()));
+ connect(client, &TorrentClient::stopped, this, &MainWindow::torrentStopped);
client->stop();
delete torrentView->takeTopLevelItem(0);
}
@@ -696,7 +704,7 @@ void MainWindow::closeEvent(QCloseEvent *)
if (jobsToStop > jobsStopped)
quitDialog->exec();
quitDialog->deleteLater();
- quitDialog = 0;
+ quitDialog = nullptr;
}
TorrentView::TorrentView(QWidget *parent)
diff --git a/examples/network/torrent/mainwindow.h b/examples/network/torrent/mainwindow.h
index 9c55b72256..78542b535b 100644
--- a/examples/network/torrent/mainwindow.h
+++ b/examples/network/torrent/mainwindow.h
@@ -71,7 +71,7 @@ class MainWindow : public QMainWindow
Q_OBJECT
public:
- MainWindow(QWidget *parent = 0);
+ MainWindow(QWidget *parent = nullptr);
QSize sizeHint() const override;
const TorrentClient *clientForRow(int row) const;
diff --git a/examples/network/torrent/peerwireclient.cpp b/examples/network/torrent/peerwireclient.cpp
index 7a53c85f0c..cea4ef53fa 100644
--- a/examples/network/torrent/peerwireclient.cpp
+++ b/examples/network/torrent/peerwireclient.cpp
@@ -87,7 +87,7 @@ PeerWireClient::PeerWireClient(const QByteArray &peerId, QObject *parent)
: QTcpSocket(parent), pendingBlockSizes(0),
pwState(ChokingPeer | ChokedByPeer), receivedHandShake(false), gotPeerId(false),
sentHandShake(false), nextPacketLength(-1), pendingRequestTimer(0), invalidateTimeout(false),
- keepAliveTimer(0), torrentPeer(0)
+ keepAliveTimer(0), torrentPeer(nullptr)
{
memset(uploadSpeedData, 0, sizeof(uploadSpeedData));
memset(downloadSpeedData, 0, sizeof(downloadSpeedData));
@@ -96,21 +96,23 @@ PeerWireClient::PeerWireClient(const QByteArray &peerId, QObject *parent)
timeoutTimer = startTimer(ConnectTimeout);
peerIdString = peerId;
- connect(this, SIGNAL(readyRead()), this, SIGNAL(readyToTransfer()));
- connect(this, SIGNAL(connected()), this, SIGNAL(readyToTransfer()));
-
- connect(&socket, SIGNAL(connected()),
- this, SIGNAL(connected()));
- connect(&socket, SIGNAL(readyRead()),
- this, SIGNAL(readyRead()));
- connect(&socket, SIGNAL(disconnected()),
- this, SIGNAL(disconnected()));
- connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)),
- this, SIGNAL(error(QAbstractSocket::SocketError)));
- connect(&socket, SIGNAL(bytesWritten(qint64)),
- this, SIGNAL(bytesWritten(qint64)));
- connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
- this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
+ connect(this, &PeerWireClient::readyRead,
+ this, &PeerWireClient::readyToTransfer);
+ connect(this, &PeerWireClient::connected,
+ this, &PeerWireClient::readyToTransfer);
+
+ connect(&socket, &QTcpSocket::connected,
+ this, &PeerWireClient::connected);
+ connect(&socket, &QTcpSocket::readyRead,
+ this, &PeerWireClient::readyRead);
+ connect(&socket, &QTcpSocket::disconnected,
+ this, &PeerWireClient::disconnected);
+ connect(&socket, QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error),
+ this, QOverload<QAbstractSocket::SocketError>::of(&PeerWireClient::error));
+ connect(&socket, &QTcpSocket::bytesWritten,
+ this, &PeerWireClient::bytesWritten);
+ connect(&socket, &QTcpSocket::stateChanged,
+ this, &PeerWireClient::socketStateChanged);
}
diff --git a/examples/network/torrent/peerwireclient.h b/examples/network/torrent/peerwireclient.h
index e03b538f63..75edf8ee77 100644
--- a/examples/network/torrent/peerwireclient.h
+++ b/examples/network/torrent/peerwireclient.h
@@ -92,7 +92,7 @@ public:
};
Q_DECLARE_FLAGS(PeerWireState, PeerWireStateFlag)
- explicit PeerWireClient(const QByteArray &peerId, QObject *parent = 0);
+ explicit PeerWireClient(const QByteArray &peerId, QObject *parent = nullptr);
void initialize(const QByteArray &infoHash, int pieceCount);
void setPeer(TorrentPeer *peer);
diff --git a/examples/network/torrent/ratecontroller.cpp b/examples/network/torrent/ratecontroller.cpp
index 96474806f5..756947b65c 100644
--- a/examples/network/torrent/ratecontroller.cpp
+++ b/examples/network/torrent/ratecontroller.cpp
@@ -62,7 +62,8 @@ RateController *RateController::instance()
void RateController::addSocket(PeerWireClient *socket)
{
- connect(socket, SIGNAL(readyToTransfer()), this, SLOT(scheduleTransfer()));
+ connect(socket, &PeerWireClient::readyToTransfer,
+ this, &RateController::scheduleTransfer);
socket->setReadBufferSize(downLimit * 4);
sockets << socket;
scheduleTransfer();
@@ -70,7 +71,8 @@ void RateController::addSocket(PeerWireClient *socket)
void RateController::removeSocket(PeerWireClient *socket)
{
- disconnect(socket, SIGNAL(readyToTransfer()), this, SLOT(scheduleTransfer()));
+ disconnect(socket, &PeerWireClient::readyToTransfer,
+ this, &RateController::scheduleTransfer);
socket->setReadBufferSize(0);
sockets.remove(socket);
}
diff --git a/examples/network/torrent/ratecontroller.h b/examples/network/torrent/ratecontroller.h
index f8bff0cc36..593a76f592 100644
--- a/examples/network/torrent/ratecontroller.h
+++ b/examples/network/torrent/ratecontroller.h
@@ -62,8 +62,7 @@ class RateController : public QObject
Q_OBJECT
public:
- inline RateController(QObject *parent = 0)
- : QObject(parent), transferScheduled(false) { }
+ using QObject::QObject;
static RateController *instance();
void addSocket(PeerWireClient *socket);
@@ -81,9 +80,9 @@ public slots:
private:
QElapsedTimer stopWatch;
QSet<PeerWireClient *> sockets;
- int upLimit;
- int downLimit;
- bool transferScheduled;
+ int upLimit = 0;
+ int downLimit = 0;
+ bool transferScheduled = false;
};
#endif
diff --git a/examples/network/torrent/torrentclient.cpp b/examples/network/torrent/torrentclient.cpp
index bddf3caa1a..00f46df892 100644
--- a/examples/network/torrent/torrentclient.cpp
+++ b/examples/network/torrent/torrentclient.cpp
@@ -75,13 +75,12 @@ static const int MinimumTimeBeforeRevisit = 30;
static const int MaxUploads = 4;
static const int UploadScheduleInterval = 10000;
-class TorrentPiece {
-public:
- int index;
- int length;
+struct TorrentPiece {
QBitArray completedBlocks;
QBitArray requestedBlocks;
- bool inProgress;
+ int index = 0;
+ int length = 0;
+ bool inProgress = false;
};
class TorrentClientPrivate
@@ -227,7 +226,7 @@ void TorrentClientPrivate::callPeerConnector()
{
if (!connectingToClients) {
connectingToClients = true;
- QTimer::singleShot(10000, q, SLOT(connectToPeers()));
+ QTimer::singleShot(10000, q, &TorrentClient::connectToPeers);
}
}
@@ -235,22 +234,22 @@ TorrentClient::TorrentClient(QObject *parent)
: QObject(parent), d(new TorrentClientPrivate(this))
{
// Connect the file manager
- connect(&d->fileManager, SIGNAL(dataRead(int,int,int,QByteArray)),
- this, SLOT(sendToPeer(int,int,int,QByteArray)));
- connect(&d->fileManager, SIGNAL(verificationProgress(int)),
- this, SLOT(updateProgress(int)));
- connect(&d->fileManager, SIGNAL(verificationDone()),
- this, SLOT(fullVerificationDone()));
- connect(&d->fileManager, SIGNAL(pieceVerified(int,bool)),
- this, SLOT(pieceVerified(int,bool)));
- connect(&d->fileManager, SIGNAL(error()),
- this, SLOT(handleFileError()));
+ connect(&d->fileManager, &FileManager::dataRead,
+ this, &TorrentClient::sendToPeer);
+ connect(&d->fileManager, &FileManager::verificationProgress,
+ this, &TorrentClient::updateProgress);
+ connect(&d->fileManager, &FileManager::verificationDone,
+ this, &TorrentClient::fullVerificationDone);
+ connect(&d->fileManager, &FileManager::pieceVerified,
+ this, &TorrentClient::pieceVerified);
+ connect(&d->fileManager, &FileManager::error,
+ this, &TorrentClient::handleFileError);
// Connect the tracker client
- connect(&d->trackerClient, SIGNAL(peerListUpdated(QList<TorrentPeer>)),
- this, SLOT(addToPeerList(QList<TorrentPeer>)));
- connect(&d->trackerClient, SIGNAL(stopped()),
- this, SIGNAL(stopped()));
+ connect(&d->trackerClient, &TrackerClient::peerListUpdated,
+ this, &TorrentClient::addToPeerList);
+ connect(&d->trackerClient, &TrackerClient::stopped,
+ this, &TorrentClient::stopped);
}
TorrentClient::~TorrentClient()
@@ -840,26 +839,26 @@ void TorrentClient::setupOutgoingConnection()
void TorrentClient::initializeConnection(PeerWireClient *client)
{
- connect(client, SIGNAL(connected()),
- this, SLOT(setupOutgoingConnection()));
- connect(client, SIGNAL(disconnected()),
- this, SLOT(removeClient()));
- connect(client, SIGNAL(error(QAbstractSocket::SocketError)),
- this, SLOT(removeClient()));
- connect(client, SIGNAL(piecesAvailable(QBitArray)),
- this, SLOT(peerPiecesAvailable(QBitArray)));
- connect(client, SIGNAL(blockRequested(int,int,int)),
- this, SLOT(peerRequestsBlock(int,int,int)));
- connect(client, SIGNAL(blockReceived(int,int,QByteArray)),
- this, SLOT(blockReceived(int,int,QByteArray)));
- connect(client, SIGNAL(choked()),
- this, SLOT(peerChoked()));
- connect(client, SIGNAL(unchoked()),
- this, SLOT(peerUnchoked()));
- connect(client, SIGNAL(bytesWritten(qint64)),
- this, SLOT(peerWireBytesWritten(qint64)));
- connect(client, SIGNAL(bytesReceived(qint64)),
- this, SLOT(peerWireBytesReceived(qint64)));
+ connect(client, &PeerWireClient::connected,
+ this, &TorrentClient::setupOutgoingConnection);
+ connect(client, &PeerWireClient::disconnected,
+ this, &TorrentClient::removeClient);
+ connect(client, QOverload<QAbstractSocket::SocketError>::of(&PeerWireClient::error),
+ this, &TorrentClient::removeClient);
+ connect(client, &PeerWireClient::piecesAvailable,
+ this, &TorrentClient::peerPiecesAvailable);
+ connect(client, &PeerWireClient::blockRequested,
+ this, &TorrentClient::peerRequestsBlock);
+ connect(client, &PeerWireClient::blockReceived,
+ this, &TorrentClient::blockReceived);
+ connect(client, &PeerWireClient::choked,
+ this, &TorrentClient::peerChoked);
+ connect(client, &PeerWireClient::unchoked,
+ this, &TorrentClient::peerUnchoked);
+ connect(client, &PeerWireClient::bytesWritten,
+ this, &TorrentClient::peerWireBytesWritten);
+ connect(client, &PeerWireClient::bytesReceived,
+ this, &TorrentClient::peerWireBytesReceived);
}
void TorrentClient::removeClient()
@@ -868,7 +867,7 @@ void TorrentClient::removeClient()
// Remove the host from our list of known peers if the connection
// failed.
- if (client->peer() && client->error() == QAbstractSocket::ConnectionRefusedError)
+ if (client->peer() && client->socketError() == QAbstractSocket::ConnectionRefusedError)
d->peers.removeAll(client->peer());
// Remove the client from RateController and all structures.
@@ -890,7 +889,8 @@ void TorrentClient::removeClient()
}
// Delete the client later.
- disconnect(client, SIGNAL(disconnected()), this, SLOT(removeClient()));
+ disconnect(client, &PeerWireClient::disconnected,
+ this, &TorrentClient::removeClient);
client->deleteLater();
ConnectionManager::instance()->removeConnection(client);
@@ -905,7 +905,7 @@ void TorrentClient::peerPiecesAvailable(const QBitArray &pieces)
// Find the peer in our list of announced peers. If it's there,
// then we can use the piece list into to gather statistics that
// help us decide what peers to connect to.
- TorrentPeer *peer = 0;
+ TorrentPeer *peer = nullptr;
QList<TorrentPeer *>::Iterator it = d->peers.begin();
while (it != d->peers.end()) {
if ((*it)->address == client->peerAddress() && (*it)->port == client->peerPort()) {
@@ -1163,7 +1163,7 @@ void TorrentClient::schedulePieceForClient(PeerWireClient *client)
// many blocks have been requested.
QList<int> currentPieces;
bool somePiecesAreNotInProgress = false;
- TorrentPiece *lastPendingPiece = 0;
+ TorrentPiece *lastPendingPiece = nullptr;
QMultiMap<PeerWireClient *, TorrentPiece *>::Iterator it = d->payloads.find(client);
while (it != d->payloads.end() && it.key() == client) {
lastPendingPiece = it.value();
@@ -1183,7 +1183,7 @@ void TorrentClient::schedulePieceForClient(PeerWireClient *client)
// If all pieces are in progress, but we haven't filled up our
// block requesting quota, then we need to schedule another piece.
if (!somePiecesAreNotInProgress || client->incomingBlocks().size() > 0)
- lastPendingPiece = 0;
+ lastPendingPiece = nullptr;
TorrentPiece *piece = lastPendingPiece;
// In warmup state, all clients request blocks from the same pieces.
diff --git a/examples/network/torrent/torrentclient.h b/examples/network/torrent/torrentclient.h
index b9b88b3a07..ad77caa66c 100644
--- a/examples/network/torrent/torrentclient.h
+++ b/examples/network/torrent/torrentclient.h
@@ -58,8 +58,7 @@
class MetaInfo;
class PeerWireClient;
class TorrentClientPrivate;
-class TorrentPeer;
-class TorrentPiece;
+struct TorrentPiece;
QT_BEGIN_NAMESPACE
class QTimerEvent;
QT_END_NAMESPACE
@@ -110,7 +109,7 @@ public:
ServerError
};
- TorrentClient(QObject *parent = 0);
+ TorrentClient(QObject *parent = nullptr);
~TorrentClient();
bool setTorrent(const QString &fileName);
diff --git a/examples/network/torrent/torrentserver.cpp b/examples/network/torrent/torrentserver.cpp
index c68f33249c..215498194b 100644
--- a/examples/network/torrent/torrentserver.cpp
+++ b/examples/network/torrent/torrentserver.cpp
@@ -78,10 +78,10 @@ void TorrentServer::incomingConnection(qintptr socketDescriptor)
if (client->setSocketDescriptor(socketDescriptor)) {
if (ConnectionManager::instance()->canAddConnection() && !clients.isEmpty()) {
- connect(client, SIGNAL(infoHashReceived(QByteArray)),
- this, SLOT(processInfoHash(QByteArray)));
- connect(client, SIGNAL(error(QAbstractSocket::SocketError)),
- this, SLOT(removeClient()));
+ connect(client, &PeerWireClient::infoHashReceived,
+ this, &TorrentServer::processInfoHash);
+ connect(client, QOverload<QAbstractSocket::SocketError>::of(&PeerWireClient::error),
+ this, QOverload<>::of(&TorrentServer::removeClient));
RateController::instance()->addSocket(client);
ConnectionManager::instance()->addConnection(client);
return;
@@ -104,7 +104,7 @@ void TorrentServer::processInfoHash(const QByteArray &infoHash)
PeerWireClient *peer = qobject_cast<PeerWireClient *>(sender());
for (TorrentClient *client : qAsConst(clients)) {
if (client->state() >= TorrentClient::Searching && client->infoHash() == infoHash) {
- peer->disconnect(peer, 0, this, 0);
+ peer->disconnect(peer, nullptr, this, nullptr);
client->setupIncomingConnection(peer);
return;
}
diff --git a/examples/network/torrent/trackerclient.cpp b/examples/network/torrent/trackerclient.cpp
index e883317b12..540ab31557 100644
--- a/examples/network/torrent/trackerclient.cpp
+++ b/examples/network/torrent/trackerclient.cpp
@@ -60,14 +60,8 @@
TrackerClient::TrackerClient(TorrentClient *downloader, QObject *parent)
: QObject(parent), torrentDownloader(downloader)
{
- length = 0;
- requestInterval = 5 * 60;
- requestIntervalTimer = -1;
- firstTrackerRequest = true;
- lastTrackerRequest = false;
- firstSeeding = true;
-
- connect(&http, SIGNAL(finished(QNetworkReply*)), this, SLOT(httpRequestDone(QNetworkReply*)));
+ connect(&http, &QNetworkAccessManager::finished,
+ this, &TrackerClient::httpRequestDone);
}
void TrackerClient::start(const MetaInfo &info)
@@ -157,8 +151,8 @@ void TrackerClient::fetchPeerList()
if (!url.userName().isEmpty()) {
uname = url.userName();
pwd = url.password();
- connect(&http, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
- this, SLOT(provideAuthentication(QNetworkReply*,QAuthenticator*)));
+ connect(&http, &QNetworkAccessManager::authenticationRequired,
+ this, &TrackerClient::provideAuthentication);
}
http.get(req);
}
@@ -171,8 +165,8 @@ void TrackerClient::httpRequestDone(QNetworkReply *reply)
return;
}
- if (reply->error() != QNetworkReply::NoError) {
- emit connectionError(reply->error());
+ if (reply->networkError() != QNetworkReply::NoError) {
+ emit connectionError(reply->networkError());
return;
}
diff --git a/examples/network/torrent/trackerclient.h b/examples/network/torrent/trackerclient.h
index 323fc67eba..b8c169ff22 100644
--- a/examples/network/torrent/trackerclient.h
+++ b/examples/network/torrent/trackerclient.h
@@ -69,7 +69,7 @@ class TrackerClient : public QObject
Q_OBJECT
public:
- explicit TrackerClient(TorrentClient *downloader, QObject *parent = 0);
+ explicit TrackerClient(TorrentClient *downloader, QObject *parent = nullptr);
void start(const MetaInfo &info);
void stop();
@@ -98,21 +98,19 @@ private slots:
private:
TorrentClient *torrentDownloader;
- int requestInterval;
- int requestIntervalTimer;
+ int requestInterval = 5 * 60;
+ int requestIntervalTimer = -1;
QNetworkAccessManager http;
MetaInfo metaInfo;
QByteArray trackerId;
QList<TorrentPeer> peers;
- qint64 uploadedBytes;
- qint64 downloadedBytes;
- qint64 length;
+ qint64 length = 0;
QString uname;
QString pwd;
- bool firstTrackerRequest;
- bool lastTrackerRequest;
- bool firstSeeding;
+ bool firstTrackerRequest = true;
+ bool lastTrackerRequest = false;
+ bool firstSeeding = true;
};
#endif
diff --git a/examples/opengl/2dpainting/2dpainting.pro b/examples/opengl/2dpainting/2dpainting.pro
index b9611f5b40..20fe4739a5 100644
--- a/examples/opengl/2dpainting/2dpainting.pro
+++ b/examples/opengl/2dpainting/2dpainting.pro
@@ -1,4 +1,4 @@
-QT += widgets
+QT += widgets opengl
HEADERS = glwidget.h \
helper.h \
diff --git a/examples/opengl/computegles31/computegles31.pro b/examples/opengl/computegles31/computegles31.pro
index 5b9d7e4387..8d9b00ba83 100644
--- a/examples/opengl/computegles31/computegles31.pro
+++ b/examples/opengl/computegles31/computegles31.pro
@@ -1,3 +1,5 @@
+QT += opengl
+
HEADERS = $$PWD/glwindow.h
SOURCES = $$PWD/glwindow.cpp \
diff --git a/examples/opengl/computegles31/glwindow.cpp b/examples/opengl/computegles31/glwindow.cpp
index 2194137cfd..5e8d45da24 100644
--- a/examples/opengl/computegles31/glwindow.cpp
+++ b/examples/opengl/computegles31/glwindow.cpp
@@ -171,7 +171,7 @@ static const char *fsDisplaySource =
"}\n";
static const char *csComputeSourceV =
- "#define COMPUTEPATCHSIZE 32 \n"
+ "#define COMPUTEPATCHSIZE 10 // Setting this to 10 to comply with MAX_COMPUTE_WORK_GROUP_INVOCATIONS for both OpenGL and OpenGLES - see QTBUG-79374 \n"
"#define IMGFMT rgba8 \n"
"layout (local_size_x = COMPUTEPATCHSIZE, local_size_y = COMPUTEPATCHSIZE) in;\n"
"layout(binding=0, IMGFMT) uniform readonly highp image2D inputImage; // Use a sampler to improve performance \n"
@@ -212,7 +212,7 @@ static const char *csComputeSourceV =
"}\n";
static const char *csComputeSourceH =
- "#define COMPUTEPATCHSIZE 32 \n"
+ "#define COMPUTEPATCHSIZE 10 \n"
"#define IMGFMT rgba8 \n"
"layout (local_size_x = COMPUTEPATCHSIZE, local_size_y = COMPUTEPATCHSIZE) in;\n"
"layout(binding=0, IMGFMT) uniform readonly highp image2D inputImage; // Use a sampler to improve performance \n"
@@ -381,7 +381,7 @@ void GLWindow::paintGL()
// Process input image
- QSize workGroups = getWorkGroups( 32, QSize(m_texImageInput->width(), m_texImageInput->height()));
+ QSize workGroups = getWorkGroups(10, QSize(m_texImageInput->width(), m_texImageInput->height()));
// Pass 1
f->glBindImageTexture(0, m_texImageInput->textureId(), 0, 0, 0, GL_READ_WRITE, GL_RGBA8);
f->glBindImageTexture(1, m_texImageTmp->textureId(), 0, 0, 0, GL_READ_WRITE, GL_RGBA8);
diff --git a/examples/opengl/cube/cube.pro b/examples/opengl/cube/cube.pro
index b9416f1a9d..07724e247e 100644
--- a/examples/opengl/cube/cube.pro
+++ b/examples/opengl/cube/cube.pro
@@ -1,4 +1,4 @@
-QT += core gui widgets
+QT += core gui widgets opengl
TARGET = cube
TEMPLATE = app
diff --git a/examples/opengl/hellogl2/hellogl2.pro b/examples/opengl/hellogl2/hellogl2.pro
index 3a52e04d74..834ae82e1f 100644
--- a/examples/opengl/hellogl2/hellogl2.pro
+++ b/examples/opengl/hellogl2/hellogl2.pro
@@ -8,7 +8,7 @@ SOURCES = glwidget.cpp \
mainwindow.cpp \
logo.cpp
-QT += widgets
+QT += widgets opengl
# install
target.path = $$[QT_INSTALL_EXAMPLES]/opengl/hellogl2
diff --git a/examples/opengl/hellogles3/hellogles3.pro b/examples/opengl/hellogles3/hellogles3.pro
index e0d4c25ca6..8d9fbe25ca 100644
--- a/examples/opengl/hellogles3/hellogles3.pro
+++ b/examples/opengl/hellogles3/hellogles3.pro
@@ -1,3 +1,5 @@
+QT += opengl
+
HEADERS = $$PWD/glwindow.h \
$$PWD/../hellogl2/logo.h
diff --git a/examples/opengl/qopenglwidget/qopenglwidget.pro b/examples/opengl/qopenglwidget/qopenglwidget.pro
index 0165285c02..1df3de1290 100644
--- a/examples/opengl/qopenglwidget/qopenglwidget.pro
+++ b/examples/opengl/qopenglwidget/qopenglwidget.pro
@@ -1,4 +1,4 @@
-QT += widgets
+QT += widgets opengl
SOURCES += main.cpp \
glwidget.cpp \
diff --git a/examples/opengl/qopenglwindow/qopenglwindow.pro b/examples/opengl/qopenglwindow/qopenglwindow.pro
index dad4b58158..e7073a324b 100644
--- a/examples/opengl/qopenglwindow/qopenglwindow.pro
+++ b/examples/opengl/qopenglwindow/qopenglwindow.pro
@@ -1,6 +1,7 @@
TEMPLATE = app
TARGET = qopenglwindow
INCLUDEPATH += .
+QT += opengl
RESOURCES += shaders.qrc
diff --git a/examples/opengl/textures/textures.pro b/examples/opengl/textures/textures.pro
index 7a7d19bee6..ae1ae4d34c 100644
--- a/examples/opengl/textures/textures.pro
+++ b/examples/opengl/textures/textures.pro
@@ -6,7 +6,7 @@ SOURCES = glwidget.cpp \
RESOURCES = textures.qrc
-QT += widgets
+QT += widgets opengl
# install
target.path = $$[QT_INSTALL_EXAMPLES]/opengl/textures
diff --git a/examples/opengl/threadedqopenglwidget/threadedqopenglwidget.pro b/examples/opengl/threadedqopenglwidget/threadedqopenglwidget.pro
index 4e941b28c4..70694459b2 100644
--- a/examples/opengl/threadedqopenglwidget/threadedqopenglwidget.pro
+++ b/examples/opengl/threadedqopenglwidget/threadedqopenglwidget.pro
@@ -1,4 +1,4 @@
-QT += widgets
+QT += widgets opengl
SOURCES += main.cpp \
glwidget.cpp \
diff --git a/examples/sql/doc/src/cachedtable.qdoc b/examples/sql/doc/src/cachedtable.qdoc
index 2db80f9c8e..0dd7928e21 100644
--- a/examples/sql/doc/src/cachedtable.qdoc
+++ b/examples/sql/doc/src/cachedtable.qdoc
@@ -43,15 +43,15 @@
\section1 TableEditor Class Definition
- The \c TableEditor class inherits QDialog making the table editor
+ The \c TableEditor class inherits QWidget making the table editor
widget a top-level dialog window.
\snippet cachedtable/tableeditor.h 0
The \c TableEditor constructor takes two arguments: The first is a
- pointer to the parent widget and is passed on to the base class
- constructor. The other is a reference to the database table the \c
- TableEditor object will operate on.
+ reference to the database table the \c TableEditor object will operate
+ on. The other is a pointer to the parent widget and is passed on to the
+ base class constructor.
Note the QSqlTableModel variable declaration: As we will see in
this example, the QSqlTableModel class can be used to provide data
diff --git a/examples/sql/masterdetail/mainwindow.cpp b/examples/sql/masterdetail/mainwindow.cpp
index 7f3479619a..2ff9a10d91 100644
--- a/examples/sql/masterdetail/mainwindow.cpp
+++ b/examples/sql/masterdetail/mainwindow.cpp
@@ -320,7 +320,7 @@ QGroupBox* MainWindow::createAlbumGroupBox()
this, &MainWindow::showAlbumDetails);
QVBoxLayout *layout = new QVBoxLayout;
- layout->addWidget(albumView, 0, 0);
+ layout->addWidget(albumView, 0, { });
box->setLayout(layout);
return box;
diff --git a/examples/widgets/animation/sub-attaq/mainwindow.cpp b/examples/widgets/animation/sub-attaq/mainwindow.cpp
index 8f545ecebd..0c152c9180 100644
--- a/examples/widgets/animation/sub-attaq/mainwindow.cpp
+++ b/examples/widgets/animation/sub-attaq/mainwindow.cpp
@@ -56,12 +56,9 @@
#include <QGraphicsView>
#include <QApplication>
#include <QMenu>
+#include <QMenuBar>
#include <QLayout>
-#ifndef QT_NO_OPENGL
-# include <QtOpenGL>
-#endif
-
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
@@ -83,14 +80,5 @@ MainWindow::MainWindow(QWidget *parent)
view = new QGraphicsView(scene, this);
view->setAlignment(Qt::AlignLeft | Qt::AlignTop);
scene->setupScene(newAction, quitAction);
-#ifndef QT_NO_OPENGL
- QGLWidget *glWidget = new QGLWidget(QGLFormat(QGL::SampleBuffers));
- if (glWidget->context()->isValid()) {
- view->setViewport(glWidget);
- } else {
- qWarning("Unable to create an Open GL context with sample buffers, not using Open GL.");
- delete glWidget;
- }
-#endif
setCentralWidget(view);
}
diff --git a/examples/widgets/animation/sub-attaq/sub-attaq.pro b/examples/widgets/animation/sub-attaq/sub-attaq.pro
index ac79fd4249..ea44253fa1 100644
--- a/examples/widgets/animation/sub-attaq/sub-attaq.pro
+++ b/examples/widgets/animation/sub-attaq/sub-attaq.pro
@@ -1,5 +1,4 @@
QT += widgets
-qtHaveModule(opengl): QT += opengl
HEADERS += boat.h \
bomb.h \
mainwindow.h \
diff --git a/examples/widgets/desktop/systray/doc/src/systray.qdoc b/examples/widgets/desktop/systray/doc/src/systray.qdoc
index fe397f83df..ae7e925bd8 100644
--- a/examples/widgets/desktop/systray/doc/src/systray.qdoc
+++ b/examples/widgets/desktop/systray/doc/src/systray.qdoc
@@ -182,6 +182,6 @@
In addition to the functions and slots discussed above, we have
also implemented several convenience functions to simplify the
constructor: \c createIconGroupBox(), \c createMessageGroupBox(),
- \c createActions() and \c createTrayIcon(). See the \l
- {desktop/systray/window.cpp}{window.cpp} file for details.
+ \c createActions() and \c createTrayIcon(). See the \c
+ {desktop/systray/window.cpp} file for details.
*/
diff --git a/examples/widgets/dialogs/standarddialogs/dialog.cpp b/examples/widgets/dialogs/standarddialogs/dialog.cpp
index df77d03567..77549e60f8 100644
--- a/examples/widgets/dialogs/standarddialogs/dialog.cpp
+++ b/examples/widgets/dialogs/standarddialogs/dialog.cpp
@@ -492,7 +492,7 @@ void Dialog::questionMessage()
void Dialog::warningMessage()
{
QMessageBox msgBox(QMessageBox::Warning, tr("QMessageBox::warning()"),
- MESSAGE, nullptr, this);
+ MESSAGE, { }, this);
msgBox.setDetailedText(MESSAGE_DETAILS);
msgBox.addButton(tr("Save &Again"), QMessageBox::AcceptRole);
msgBox.addButton(tr("&Continue"), QMessageBox::RejectRole);
diff --git a/examples/widgets/doc/src/addressbook-tutorial.qdoc b/examples/widgets/doc/src/addressbook-tutorial.qdoc
index 1f6966e8ae..563b6a2be9 100644
--- a/examples/widgets/doc/src/addressbook-tutorial.qdoc
+++ b/examples/widgets/doc/src/addressbook-tutorial.qdoc
@@ -136,7 +136,7 @@
\section1 Defining the AddressBook Class
- The \l{tutorials/addressbook/part1/addressbook.h}{\c addressbook.h} file is
+ The \c{tutorials/addressbook/part1/addressbook.h} file is
used to define the \c AddressBook class.
We start by defining \c AddressBook as a QWidget subclass and declaring
diff --git a/examples/widgets/doc/src/customsortfiltermodel.qdoc b/examples/widgets/doc/src/customsortfiltermodel.qdoc
index 9f0d13dd83..97725ead04 100644
--- a/examples/widgets/doc/src/customsortfiltermodel.qdoc
+++ b/examples/widgets/doc/src/customsortfiltermodel.qdoc
@@ -284,6 +284,6 @@
instance of the QStandardItemModel class, i.e., a generic model
for storing custom data typically used as a repository for
standard Qt data types. Each mail description is added to the
- model using \c addMail(), another convenience function. See \l
- {itemviews/customsortfiltermodel/main.cpp}{main.cpp} for details.
+ model using \c addMail(), another convenience function. See \c
+ {itemviews/customsortfiltermodel/main.cpp} for details.
*/
diff --git a/examples/xml/saxbookmarks/doc/src/saxbookmarks.qdoc b/examples/widgets/doc/src/gallery.qdoc
index 0cd89e641e..a262374ce6 100644
--- a/examples/xml/saxbookmarks/doc/src/saxbookmarks.qdoc
+++ b/examples/widgets/doc/src/gallery.qdoc
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2020 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
@@ -26,16 +26,11 @@
****************************************************************************/
/*!
- \example saxbookmarks
- \title SAX Bookmarks Example
- \brief Demonstrates how to read XBEL files.
- \ingroup xml-examples
+ \example widgets/gallery
+ \title Widgets Gallery Example
+ \ingroup examples-widgets
+ \brief The Widgets Gallery example shows widgets relevant for designing UIs.
- This example uses Qt's SAX API to read and parse the files. The DOM Bookmarks
- example provides an alternative way to read this type of file.
-
- \image saxbookmarks-example.png
-
- See the \l{XML Bookmark Exchange Language Resource Page} for more
- information about XBEL files.
+ This example demonstrates widgets typically used in dialogs and forms.
+ It also allows for changing the style.
*/
diff --git a/examples/widgets/doc/src/icons.qdoc b/examples/widgets/doc/src/icons.qdoc
index 7aae0491d6..24be09a7a9 100644
--- a/examples/widgets/doc/src/icons.qdoc
+++ b/examples/widgets/doc/src/icons.qdoc
@@ -232,8 +232,8 @@
combinations of states and modes for a given icon.
\li \c IconSizeSpinBox is a subclass of QSpinBox that lets the
user enter icon sizes (e.g., "48 x 48").
- \li \c ImageDelegate is a subclass of QItemDelegate that provides
- comboboxes for letting the user set the mode and state
+ \li \c ImageDelegate is a subclass of QStyledItemDelegate that
+ provides comboboxes for letting the user set the mode and state
associated with an image.
\endlist
@@ -468,7 +468,6 @@
loaded into the application.
\snippet widgets/icons/mainwindow.cpp 13
- \snippet widgets/icons/mainwindow.cpp 14
We retrieve the image name using the QFileInfo::baseName()
function that returns the base name of the file without the path,
@@ -486,8 +485,6 @@
Qt::ItemIsEditable flag. Table items are editable by default.
\snippet widgets/icons/mainwindow.cpp 15
- \snippet widgets/icons/mainwindow.cpp 16
- \snippet widgets/icons/mainwindow.cpp 17
Then we create the second and third items in the row making the
default mode Normal and the default state Off. But if the \uicontrol
@@ -498,7 +495,6 @@
example's \c images subdirectory respect this naming convention.
\snippet widgets/icons/mainwindow.cpp 18
- \snippet widgets/icons/mainwindow.cpp 19
In the end we add the items to the associated row, and use the
QTableWidget::openPersistentEditor() function to create
@@ -522,8 +518,6 @@
application.
\snippet widgets/icons/mainwindow.cpp 8
- \snippet widgets/icons/mainwindow.cpp 9
- \snippet widgets/icons/mainwindow.cpp 10
We also extract the image file's name using the
QTableWidgetItem::data() function. This function takes a
@@ -571,24 +565,22 @@
delegate for the table widget. We create a \c ImageDelegate that
we make the item delegate for our view.
- The QItemDelegate class can be used to provide an editor for an item view
+ The QStyledItemDelegate class can be used to provide an editor for an item view
class that is subclassed from QAbstractItemView. Using a delegate
for this purpose allows the editing mechanism to be customized and
developed independently from the model and view.
- In this example we derive \c ImageDelegate from QItemDelegate.
- QItemDelegate usually provides line editors, while our subclass
+ In this example we derive \c ImageDelegate from QStyledItemDelegate.
+ QStyledItemDelegate usually provides line editors, while our subclass
\c ImageDelegate, provides comboboxes for the mode and state
fields.
\snippet widgets/icons/mainwindow.cpp 22
- \snippet widgets/icons/mainwindow.cpp 23
Then we customize the QTableWidget's horizontal header, and hide
the vertical header.
\snippet widgets/icons/mainwindow.cpp 24
- \snippet widgets/icons/mainwindow.cpp 25
At the end, we connect the QTableWidget::itemChanged() signal to
the \c changeIcon() slot to ensure that the preview area is in
@@ -750,23 +742,23 @@
\snippet widgets/icons/imagedelegate.h 0
- The \c ImageDelegate class is a subclass of QItemDelegate. The
- QItemDelegate class provides display and editing facilities for
- data items from a model. A single QItemDelegate object is
+ The \c ImageDelegate class is a subclass of QStyledItemDelegate. The
+ QStyledItemDelegate class provides display and editing facilities for
+ data items from a model. A single QStyledItemDelegate object is
responsible for all items displayed in a item view (in our case,
a QTableWidget).
- A QItemDelegate can be used to provide an editor for an item view
+ A QStyledItemDelegate can be used to provide an editor for an item view
class that is subclassed from QAbstractItemView. Using a delegate
for this purpose allows the editing mechanism to be customized and
developed independently from the model and view.
\snippet widgets/icons/imagedelegate.h 1
- The default implementation of QItemDelegate creates a QLineEdit.
+ The default implementation of QStyledItemDelegate creates a QLineEdit.
Since we want the editor to be a QComboBox, we need to subclass
- QItemDelegate and reimplement the QItemDelegate::createEditor(),
- QItemDelegate::setEditorData() and QItemDelegate::setModelData()
+ QStyledItemDelegate and reimplement the QStyledItemDelegate::createEditor(),
+ QStyledItemDelegate::setEditorData() and QStyledItemDelegate::setModelData()
functions.
\snippet widgets/icons/imagedelegate.h 2
@@ -783,7 +775,7 @@
\snippet widgets/icons/imagedelegate.cpp 1
- The default QItemDelegate::createEditor() implementation returns
+ The default QStyledItemDelegate::createEditor() implementation returns
the widget used to edit the item specified by the model and item
index for editing. The parent widget and style option are used to
control the appearance of the editor widget.
@@ -803,7 +795,7 @@
\snippet widgets/icons/imagedelegate.cpp 2
- The QItemDelegate::setEditorData() function is used by
+ The QStyledItemDelegate::setEditorData() function is used by
QTableWidget to transfer data from a QTableWidgetItem to the
editor. The data is stored as a string; we use
QComboBox::findText() to locate it in the combobox.
@@ -816,7 +808,7 @@
\snippet widgets/icons/imagedelegate.cpp 3
- The QItemDelegate::setEditorData() function is used by QTableWidget
+ The QStyledItemDelegate::setEditorData() function is used by QTableWidget
to transfer data back from the editor to the \l{QTableWidgetItem}.
\snippet widgets/icons/imagedelegate.cpp 4
diff --git a/examples/widgets/doc/src/padnavigator.qdoc b/examples/widgets/doc/src/padnavigator.qdoc
index e59fa3cdbe..d8e83978cf 100644
--- a/examples/widgets/doc/src/padnavigator.qdoc
+++ b/examples/widgets/doc/src/padnavigator.qdoc
@@ -387,17 +387,12 @@
\snippet graphicsview/padnavigator/padnavigator.cpp 7
We now create the animations that control the flip-effect when you press
- the enter key. The main goal is to rotate the pad by 180 degrees or back,
- but we also need to make sure the selection item's tilt rotations are reset
- back to 0 when the pad is flipped, and restored back to their original
- values when flipped back:
+ the enter key. The main goal is to rotate the pad by 180 degrees or back.
\list
\li \c smoothFlipRotation: Animates the main 180 degree rotation of the pad.
\li \c smoothFlipScale: Scales the pad out and then in again while the pad is rotating.
- \li \c smoothFlipXRotation: Animates the selection item's X-tilt to 0 and back.
- \li \c smoothFlipYRotation: Animates the selection item's Y-tilt to 0 and back.
- \li \c flipAnimation: A parallel animation group that ensures all the above animations are run in parallel.
+ \li \c flipAnimation: A parallel animation group that ensures the above animations are run in parallel.
\endlist
All animations are given a 500 millisecond duration and an
@@ -447,11 +442,17 @@
Each state assigns specific properties to objects on entry. Most
interesting perhaps is the assignment of the value 0.0 to the pad's \c
flipRotation angle property when in \c frontState, and 180.0 when in \c
- backState. At the end of this section we register default animations with
- the state engine; these animations will apply to their respective objects
- and properties for any state transition. Otherwise it's common to assign
+ backState.
+
+ At the end of this section we register default animations with the state
+ engine; these animations will apply to their respective objects and
+ properties for any state transition. Otherwise it's common to assign
animations to specific transitions.
+ Specifically, we use default animations to control the selection item's
+ movement and tilt rotations. The tilt rotations are set to 0 when the pad
+ is flipped, and restored back to their original values when flipped back.
+
The \c splashState state is set as the initial state. This is required
before we start the state engine. We proceed with creating some
transitions.
diff --git a/examples/widgets/doc/src/shapedclock.qdoc b/examples/widgets/doc/src/shapedclock.qdoc
index 2e5d8b1496..732820cdc8 100644
--- a/examples/widgets/doc/src/shapedclock.qdoc
+++ b/examples/widgets/doc/src/shapedclock.qdoc
@@ -29,16 +29,18 @@
\example widgets/shapedclock
\title Shaped Clock Example
\ingroup examples-widgets
- \brief The Shaped Clock example shows how to apply a widget mask to a top-level
- widget to produce a shaped window.
+ \brief The Shaped Clock example shows how to apply a translucent background
+ and a widget mask to a top-level widget to produce a shaped window.
\borderedimage shapedclock-example.png
- Widget masks are used to customize the shapes of top-level widgets by restricting
- the available area for painting. On some window systems, setting certain window flags
- will cause the window decoration (title bar, window frame, buttons) to be disabled,
- allowing specially-shaped windows to be created. In this example, we use this feature
- to create a circular window containing an analog clock.
+ Widget masks are used to customize the shapes of top-level widgets by
+ restricting the area available for painting and mouse input. Using a
+ translucent background facilitates partially transparent windows and smooth
+ edges. On most window systems, setting certain window flags will cause the
+ window decoration (title bar, window frame, buttons) to be disabled,
+ allowing specially-shaped windows to be created. In this example, we use
+ this feature to create a circular window containing an analog clock.
Since this example's window does not provide a \uicontrol File menu or a close
button, we provide a context menu with an \uicontrol Exit entry so that the example
@@ -52,8 +54,10 @@
\snippet widgets/shapedclock/shapedclock.h 0
- The \l{QWidget::paintEvent()}{paintEvent()} implementation is the same as that found
- in the \c AnalogClock class. We implement \l{QWidget::sizeHint()}{sizeHint()}
+ The \l{QWidget::paintEvent()}{paintEvent()} implementation is the same as
+ that found in the \c AnalogClock class, with one important exception: we
+ now must also draw background (the clock face) ourselves, since the widget
+ background is just transparent. We implement \l{QWidget::sizeHint()}{sizeHint()}
so that we don't have to resize the widget explicitly. We also provide an event
handler for resize events. This allows us to update the mask if the clock is resized.
@@ -70,9 +74,11 @@
\snippet widgets/shapedclock/shapedclock.cpp 0
- We inform the window manager that the widget is not to be decorated with a window
- frame by setting the Qt::FramelessWindowHint flag on the widget. As a result, we need
- to provide a way for the user to move the clock around the screen.
+ We request a transparent window by setting the Qt::WA_TranslucentBackground
+ widget attribute. We inform the window manager that the widget is not to be
+ decorated with a window frame by setting the Qt::FramelessWindowHint flag
+ on the widget. As a result, we need to provide a way for the user to move
+ the clock around the screen.
Mouse button events are delivered to the \c mousePressEvent() handler:
@@ -94,14 +100,20 @@
widget is moved to the point given by subtracting the \c dragPosition from the current
cursor position in global coordinates. If we drag the widget, we also accept the event.
- The \c paintEvent() function is given for completeness. See the
- \l{Analog Clock Example}{Analog Clock} example for a description of the process used
- to render the clock.
+ The \c paintEvent() function is mainly the same as described in the
+ \l{Analog Clock Example}{Analog Clock} example. The one addition is that we
+ use QPainter::drawEllipse() to draw a round clock face with the current
+ palette's default background color. We make the clock face a bit smaller
+ than the widget mask, so that the anti-aliased, semi-transparent pixels on
+ the edge are not clipped away by the widget mask. This gives the shaped
+ window smooth edges on the screen.
\snippet widgets/shapedclock/shapedclock.cpp 3
- In the \c resizeEvent() handler, we re-use some of the code from the \c paintEvent()
- to determine the region of the widget that is visible to the user:
+ In the \c resizeEvent() handler, we re-use some of the code from the \c
+ paintEvent() to determine the region of the widget that is visible to the
+ user. This tells the system the area where mouse clicks should go to us,
+ and not to whatever window is behind us:
\snippet widgets/shapedclock/shapedclock.cpp 4
@@ -121,6 +133,12 @@
\section1 Notes on Widget Masks
+ Widget masks are used to hint to the window system that the application
+ does not want mouse events for areas outside the mask. On most systems,
+ they also result in coarse visual clipping. To get smooth window edges, one
+ should use translucent background and anti-aliased painting, as shown in
+ this example.
+
Since QRegion allows arbitrarily complex regions to be created, widget masks can be
made to suit the most unconventionally-shaped windows, and even allow widgets to be
displayed with holes in them.
diff --git a/examples/widgets/doc/src/styles.qdoc b/examples/widgets/doc/src/styles.qdoc
index 4fea8f3bfc..014541a330 100644
--- a/examples/widgets/doc/src/styles.qdoc
+++ b/examples/widgets/doc/src/styles.qdoc
@@ -84,8 +84,8 @@
\snippet widgets/styles/norwegianwoodstyle.cpp 0
- The \c polish() function is reimplemented from QStyle. It takes a
- QPalette as a reference and adapts the palette to fit the style.
+ The \c standardPalette() function is reimplemented from QStyle.
+ It returns a QPalette with the style's preferred colors and textures.
Most styles don't need to reimplement that function. The
Norwegian Wood style reimplements it to set a "wooden" palette.
@@ -380,7 +380,7 @@
a certain \l{QPalette::ColorRole}{color role}, for all three
\l{QPalette::ColorGroup}{color groups} (active, disabled,
inactive). We used it to initialize the Norwegian Wood palette in
- \c polish(QPalette &).
+ \c standardPalette.
\snippet widgets/styles/norwegianwoodstyle.cpp 39
\snippet widgets/styles/norwegianwoodstyle.cpp 40
@@ -443,10 +443,6 @@
current style's \l{QStyle::standardPalette()}{standard palette}
is used; otherwise, the system's default palette is honored.
- For the Norwegian Wood style, this makes no difference because we
- always override the palette with our own palette in \c
- NorwegianWoodStyle::polish().
-
\snippet widgets/styles/widgetgallery.cpp 9
\snippet widgets/styles/widgetgallery.cpp 10
diff --git a/examples/widgets/doc/src/transformations.qdoc b/examples/widgets/doc/src/transformations.qdoc
index d67e315848..17b540b6cc 100644
--- a/examples/widgets/doc/src/transformations.qdoc
+++ b/examples/widgets/doc/src/transformations.qdoc
@@ -320,8 +320,8 @@
The \c setupShapes() function is called from the constructor and
create the QPainterPath objects representing the shapes that are
- used in the application. For construction details, see the \l
- {painting/transformations/window.cpp}{window.cpp} example
+ used in the application. For construction details, see the \c
+ {painting/transformations/window.cpp} example
file. The shapes are stored in a QList. The QList::append()
function inserts the given shape at the end of the list.
diff --git a/examples/widgets/gallery/gallery.pro b/examples/widgets/gallery/gallery.pro
new file mode 100644
index 0000000000..38bf8d6d8e
--- /dev/null
+++ b/examples/widgets/gallery/gallery.pro
@@ -0,0 +1,10 @@
+QT += widgets
+requires(qtConfig(combobox))
+
+HEADERS = widgetgallery.h
+SOURCES = main.cpp \
+ widgetgallery.cpp
+
+# install
+target.path = $$[QT_INSTALL_EXAMPLES]/widgets/gallery
+INSTALLS += target
diff --git a/examples/xml/saxbookmarks/main.cpp b/examples/widgets/gallery/main.cpp
index 8e577ca700..7f1782c84e 100644
--- a/examples/xml/saxbookmarks/main.cpp
+++ b/examples/widgets/gallery/main.cpp
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2020 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
@@ -50,13 +50,26 @@
#include <QApplication>
-#include "mainwindow.h"
+#include "widgetgallery.h"
int main(int argc, char *argv[])
{
+ bool useHighDpiScaling = true;
+
+ for (int i = 1; i < argc; ++i) {
+ if (qstrcmp(argv[i], "--no-scaling") == 0)
+ useHighDpiScaling = false;
+ }
+
+ if (useHighDpiScaling) {
+ QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
+ QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
+ } else {
+ QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
+ }
+
QApplication app(argc, argv);
- MainWindow mainWin;
- mainWin.show();
- mainWin.open();
- return app.exec();
+ WidgetGallery gallery;
+ gallery.show();
+ return QCoreApplication::exec();
}
diff --git a/examples/widgets/gallery/widgetgallery.cpp b/examples/widgets/gallery/widgetgallery.cpp
new file mode 100644
index 0000000000..3bbe8943d1
--- /dev/null
+++ b/examples/widgets/gallery/widgetgallery.cpp
@@ -0,0 +1,474 @@
+/****************************************************************************
+**
+** Copyright (C) 2020 The Qt Company Ltd.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the examples of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:BSD$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and The Qt Company. For licensing terms
+** and conditions see https://www.qt.io/terms-conditions. For further
+** information use the contact form at https://www.qt.io/contact-us.
+**
+** BSD License Usage
+** Alternatively, 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 The Qt Company Ltd 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 "widgetgallery.h"
+
+#include <QApplication>
+#include <QCheckBox>
+#include <QComboBox>
+#include <QCommandLinkButton>
+#include <QDateTimeEdit>
+#include <QDial>
+#include <QDialogButtonBox>
+#include <QFileSystemModel>
+#include <QGridLayout>
+#include <QGroupBox>
+#include <QMenu>
+#include <QLabel>
+#include <QLineEdit>
+#include <QListWidget>
+#include <QPlainTextEdit>
+#include <QProgressBar>
+#include <QPushButton>
+#include <QRadioButton>
+#include <QScrollBar>
+#include <QShortcut>
+#include <QSpinBox>
+#include <QStandardItemModel>
+#include <QStyle>
+#include <QStyleFactory>
+#include <QTextBrowser>
+#include <QTreeView>
+#include <QTableWidget>
+#include <QTextEdit>
+#include <QToolBox>
+#include <QToolButton>
+
+#include <QIcon>
+#include <QDesktopServices>
+#include <QScreen>
+#include <QWindow>
+
+#include <QDebug>
+#include <QLibraryInfo>
+#include <QSysInfo>
+#include <QTextStream>
+#include <QTimer>
+
+static inline QString className(const QObject *o)
+{
+ return QString::fromUtf8(o->metaObject()->className());
+}
+
+static inline void setClassNameToolTip(QWidget *w)
+{
+ w->setToolTip(className(w));
+}
+
+static QString helpUrl(const QString &page)
+{
+ QString result;
+ QTextStream(&result) << "https://doc.qt.io/qt-" << QT_VERSION_MAJOR
+ << '/' << page << ".html";
+ return result;
+}
+
+static inline QString helpUrl(const QWidget *w)
+{
+ return helpUrl(className(w).toLower());
+}
+
+static void launchHelp(const QWidget *w)
+{
+ QDesktopServices::openUrl(helpUrl(w));
+}
+
+static void launchModuleHelp()
+{
+ QDesktopServices::openUrl(helpUrl(QLatin1String("qtwidgets-index")));
+}
+
+template <class Widget>
+Widget *createWidget(const char *name, QWidget *parent = nullptr)
+{
+ auto result = new Widget(parent);
+ result->setObjectName(QLatin1String(name));
+ setClassNameToolTip(result);
+ return result;
+}
+
+template <class Widget, class Parameter>
+Widget *createWidget1(const Parameter &p1, const char *name, QWidget *parent = nullptr)
+{
+ auto result = new Widget(p1, parent);
+ result->setObjectName(QLatin1String(name));
+ setClassNameToolTip(result);
+ return result;
+}
+
+QTextStream &operator<<(QTextStream &str, const QRect &r)
+{
+ str << r.width() << 'x' << r.height() << Qt::forcesign << r.x() << r.y()
+ << Qt::noforcesign;
+ return str;
+}
+
+static QString highDpiScaleFactorRoundingPolicy()
+{
+ QString result;
+ QDebug(&result) << QGuiApplication::highDpiScaleFactorRoundingPolicy();
+ if (result.endsWith(QLatin1Char(')')))
+ result.chop(1);
+ const int lastSep = result.lastIndexOf(QLatin1String("::"));
+ if (lastSep != -1)
+ result.remove(0, lastSep + 2);
+ return result;
+}
+
+WidgetGallery::WidgetGallery(QWidget *parent)
+ : QDialog(parent)
+ , progressBar(createProgressBar())
+{
+ setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
+
+ auto styleComboBox = createWidget<QComboBox>("styleComboBox");
+ const QString defaultStyleName = QApplication::style()->objectName();
+ QStringList styleNames = QStyleFactory::keys();
+ for (int i = 1, size = styleNames.size(); i < size; ++i) {
+ if (defaultStyleName.compare(styleNames.at(i), Qt::CaseInsensitive) == 0) {
+ styleNames.swapItemsAt(0, i);
+ break;
+ }
+ }
+ styleComboBox->addItems(styleNames);
+
+ auto styleLabel = createWidget1<QLabel>(tr("&Style:"), "styleLabel");
+ styleLabel->setBuddy(styleComboBox);
+
+ auto helpLabel = createWidget1<QLabel>(tr("Press F1 over a widget to see Documentation"), "helpLabel");
+
+ auto disableWidgetsCheckBox = createWidget1<QCheckBox>(tr("&Disable widgets"), "disableWidgetsCheckBox");
+
+ auto buttonsGroupBox = createButtonsGroupBox();
+ auto itemViewTabWidget = createItemViewTabWidget();
+ auto simpleInputWidgetsGroupBox = createSimpleInputWidgetsGroupBox();
+ auto textToolBox = createTextToolBox();
+
+ connect(styleComboBox, &QComboBox::textActivated,
+ this, &WidgetGallery::changeStyle);
+ connect(disableWidgetsCheckBox, &QCheckBox::toggled,
+ buttonsGroupBox, &QWidget::setDisabled);
+ connect(disableWidgetsCheckBox, &QCheckBox::toggled,
+ textToolBox, &QWidget::setDisabled);
+ connect(disableWidgetsCheckBox, &QCheckBox::toggled,
+ itemViewTabWidget, &QWidget::setDisabled);
+ connect(disableWidgetsCheckBox, &QCheckBox::toggled,
+ simpleInputWidgetsGroupBox, &QWidget::setDisabled);
+
+ auto topLayout = new QHBoxLayout;
+ topLayout->addWidget(styleLabel);
+ topLayout->addWidget(styleComboBox);
+ topLayout->addStretch(1);
+ topLayout->addWidget(helpLabel);
+ topLayout->addStretch(1);
+ topLayout->addWidget(disableWidgetsCheckBox);
+
+ auto dialogButtonBox = createWidget1<QDialogButtonBox>(QDialogButtonBox::Help | QDialogButtonBox::Close,
+ "dialogButtonBox");
+ connect(dialogButtonBox, &QDialogButtonBox::helpRequested, this, launchModuleHelp);
+ connect(dialogButtonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
+
+ auto mainLayout = new QGridLayout(this);
+ mainLayout->addLayout(topLayout, 0, 0, 1, 2);
+ mainLayout->addWidget(buttonsGroupBox, 1, 0);
+ mainLayout->addWidget(simpleInputWidgetsGroupBox, 1, 1);
+ mainLayout->addWidget(itemViewTabWidget, 2, 0);
+ mainLayout->addWidget(textToolBox, 2, 1);
+ mainLayout->addWidget(progressBar, 3, 0, 1, 2);
+ mainLayout->addWidget(dialogButtonBox, 4, 0, 1, 2);
+
+ setWindowTitle(tr("Widget Gallery Qt %1").arg(QT_VERSION_STR));
+
+ new QShortcut(QKeySequence::HelpContents, this, this, &WidgetGallery::helpOnCurrentWidget);
+}
+
+void WidgetGallery::setVisible(bool visible)
+{
+ QDialog::setVisible(visible);
+ if (visible) {
+ connect(windowHandle(), &QWindow::screenChanged, this, &WidgetGallery::updateSystemInfo);
+ updateSystemInfo();
+ }
+}
+
+void WidgetGallery::changeStyle(const QString &styleName)
+{
+ QApplication::setStyle(QStyleFactory::create(styleName));
+}
+
+void WidgetGallery::advanceProgressBar()
+{
+ int curVal = progressBar->value();
+ int maxVal = progressBar->maximum();
+ progressBar->setValue(curVal + (maxVal - curVal) / 100);
+}
+
+QGroupBox *WidgetGallery::createButtonsGroupBox()
+{
+ auto result = createWidget1<QGroupBox>(tr("Buttons"), "buttonsGroupBox");
+
+ auto defaultPushButton = createWidget1<QPushButton>(tr("Default Push Button"), "defaultPushButton");
+ defaultPushButton->setDefault(true);
+
+ auto togglePushButton = createWidget1<QPushButton>(tr("Toggle Push Button"), "togglePushButton");
+ togglePushButton->setCheckable(true);
+ togglePushButton->setChecked(true);
+
+ auto flatPushButton = createWidget1<QPushButton>(tr("Flat Push Button"), "flatPushButton");
+ flatPushButton->setFlat(true);
+
+ auto toolButton = createWidget<QToolButton>("toolButton");
+ toolButton->setText(tr("Tool Button"));
+
+ auto menuToolButton = createWidget<QToolButton>("menuButton");
+ menuToolButton->setText(tr("Menu Button"));
+ auto toolMenu = new QMenu(menuToolButton);
+ menuToolButton->setPopupMode(QToolButton::InstantPopup);
+ toolMenu->addAction("Option");
+ toolMenu->addSeparator();
+ auto action = toolMenu->addAction("Checkable Option");
+ action->setCheckable(true);
+ menuToolButton->setMenu(toolMenu);
+ auto toolLayout = new QHBoxLayout;
+ toolLayout->addWidget(toolButton);
+ toolLayout->addWidget(menuToolButton);
+
+ auto commandLinkButton = createWidget1<QCommandLinkButton>(tr("Command Link Button"), "commandLinkButton");
+ commandLinkButton->setDescription(tr("Description"));
+
+ auto buttonLayout = new QVBoxLayout;
+ buttonLayout->addWidget(defaultPushButton);
+ buttonLayout->addWidget(togglePushButton);
+ buttonLayout->addWidget(flatPushButton);
+ buttonLayout->addLayout(toolLayout);
+ buttonLayout->addWidget(commandLinkButton);
+ buttonLayout->addStretch(1);
+
+ auto radioButton1 = createWidget1<QRadioButton>(tr("Radio button 1"), "radioButton1");
+ auto radioButton2 = createWidget1<QRadioButton>(tr("Radio button 2"), "radioButton2");
+ auto radioButton3 = createWidget1<QRadioButton>(tr("Radio button 3"), "radioButton3");
+ radioButton1->setChecked(true);
+
+ auto checkBox = createWidget1<QCheckBox>(tr("Tri-state check box"), "checkBox");
+ checkBox->setTristate(true);
+ checkBox->setCheckState(Qt::PartiallyChecked);
+
+ auto checkableLayout = new QVBoxLayout;
+ checkableLayout->addWidget(radioButton1);
+ checkableLayout->addWidget(radioButton2);
+ checkableLayout->addWidget(radioButton3);
+ checkableLayout->addWidget(checkBox);
+ checkableLayout->addStretch(1);
+
+ auto mainLayout = new QHBoxLayout(result);
+ mainLayout->addLayout(buttonLayout);
+ mainLayout->addLayout(checkableLayout);
+ mainLayout->addStretch();
+ return result;
+}
+
+static QWidget *embedIntoHBoxLayout(QWidget *w, int margin = 5)
+{
+ auto result = new QWidget;
+ auto layout = new QHBoxLayout(result);
+ layout->setContentsMargins(margin, margin, margin, margin);
+ layout->addWidget(w);
+ return result;
+}
+
+QToolBox *WidgetGallery::createTextToolBox()
+{
+ auto result = createWidget<QToolBox>("toolBox");
+
+ const QString plainText = tr("Twinkle, twinkle, little star,\n"
+ "How I wonder what you are.\n"
+ "Up above the world so high,\n"
+ "Like a diamond in the sky.\n"
+ "Twinkle, twinkle, little star,\n"
+ "How I wonder what you are!\n");
+ // Create centered/italic HTML rich text
+ QString richText = QLatin1String("<html><head/><body><i>");
+ for (const auto &line : plainText.splitRef(QLatin1Char('\n')))
+ richText += QLatin1String("<center>") + line + QLatin1String("</center>");
+ richText += QLatin1String("</i></body></html>");
+
+ auto textEdit = createWidget1<QTextEdit>(richText, "textEdit");
+ auto plainTextEdit = createWidget1<QPlainTextEdit>(plainText, "plainTextEdit");
+
+ systemInfoTextBrowser = createWidget<QTextBrowser>("systemInfoTextBrowser");
+
+ result->addItem(embedIntoHBoxLayout(textEdit), tr("Text Edit"));
+ result->addItem(embedIntoHBoxLayout(plainTextEdit), tr("Plain Text Edit"));
+ result->addItem(embedIntoHBoxLayout(systemInfoTextBrowser), tr("Text Browser"));
+ return result;
+}
+
+QTabWidget *WidgetGallery::createItemViewTabWidget()
+{
+ auto result = createWidget<QTabWidget>("bottomLeftTabWidget");
+ result->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored);
+
+ auto treeView = createWidget<QTreeView>("treeView");
+ auto fileSystemModel = new QFileSystemModel(treeView);
+ fileSystemModel->setRootPath(QDir::rootPath());
+ treeView->setModel(fileSystemModel);
+
+ auto tableWidget = createWidget<QTableWidget>("tableWidget");
+ tableWidget->setRowCount(10);
+ tableWidget->setColumnCount(10);
+
+ auto listModel = new QStandardItemModel(0, 1, result);
+ listModel->appendRow(new QStandardItem(QIcon(QLatin1String(":/qt-project.org/styles/commonstyle/images/diropen-128.png")),
+ tr("Directory")));
+ listModel->appendRow(new QStandardItem(QIcon(QLatin1String(":/qt-project.org/styles/commonstyle/images/computer-32.png")),
+ tr("Computer")));
+
+ auto listView = createWidget<QListView>("listView");
+ listView->setModel(listModel);
+
+ auto iconModeListView = createWidget<QListView>("iconModeListView");
+ iconModeListView->setViewMode(QListView::IconMode);
+ iconModeListView->setModel(listModel);
+
+ result->addTab(embedIntoHBoxLayout(treeView), tr("&Tree View"));
+ result->addTab(embedIntoHBoxLayout(tableWidget), tr("T&able"));
+ result->addTab(embedIntoHBoxLayout(listView), tr("&List"));
+ result->addTab(embedIntoHBoxLayout(iconModeListView), tr("&Icon Mode List"));
+ return result;
+}
+
+QGroupBox *WidgetGallery::createSimpleInputWidgetsGroupBox()
+{
+ auto result = createWidget1<QGroupBox>(tr("Simple Input Widgets"), "bottomRightGroupBox");
+ result->setCheckable(true);
+ result->setChecked(true);
+
+ auto lineEdit = createWidget1<QLineEdit>("s3cRe7", "lineEdit");
+ lineEdit->setClearButtonEnabled(true);
+ lineEdit->setEchoMode(QLineEdit::Password);
+
+ auto spinBox = createWidget<QSpinBox>("spinBox", result);
+ spinBox->setValue(50);
+
+ auto dateTimeEdit = createWidget<QDateTimeEdit>("dateTimeEdit", result);
+ dateTimeEdit->setDateTime(QDateTime::currentDateTime());
+
+ auto slider = createWidget<QSlider>("slider", result);
+ slider->setOrientation(Qt::Horizontal);
+ slider->setValue(40);
+
+ auto scrollBar = createWidget<QScrollBar>("scrollBar", result);
+ scrollBar->setOrientation(Qt::Horizontal);
+ setClassNameToolTip(scrollBar);
+ scrollBar->setValue(60);
+
+ auto dial = createWidget<QDial>("dial", result);
+ dial->setValue(30);
+ dial->setNotchesVisible(true);
+
+ auto layout = new QGridLayout(result);
+ layout->addWidget(lineEdit, 0, 0, 1, 2);
+ layout->addWidget(spinBox, 1, 0, 1, 2);
+ layout->addWidget(dateTimeEdit, 2, 0, 1, 2);
+ layout->addWidget(slider, 3, 0);
+ layout->addWidget(scrollBar, 4, 0);
+ layout->addWidget(dial, 3, 1, 2, 1);
+ layout->setRowStretch(5, 1);
+ return result;
+}
+
+QProgressBar *WidgetGallery::createProgressBar()
+{
+ auto result = createWidget<QProgressBar>("progressBar");
+ result->setRange(0, 10000);
+ result->setValue(0);
+
+ auto timer = new QTimer(this);
+ connect(timer, &QTimer::timeout, this, &WidgetGallery::advanceProgressBar);
+ timer->start(1000);
+ return result;
+}
+
+void WidgetGallery::updateSystemInfo()
+{
+ QString systemInfo;
+ QTextStream str(&systemInfo);
+ str << "<html><head/><body><h3>Build</h3><p>" << QLibraryInfo::build() << "</p>"
+ << "<h3>Operating System</h3><p>" << QSysInfo::prettyProductName() << "</p>"
+ << "<h3>Screens</h3><p>High DPI scale factor rounding policy: "
+ << highDpiScaleFactorRoundingPolicy() << "</p><ol>";
+ const auto screens = QGuiApplication::screens();
+ for (auto screen : screens) {
+ const bool current = screen == this->screen();
+ str << "<li>";
+ if (current)
+ str << "<i>";
+ str << '"' << screen->name() << "\" " << screen->geometry() << ", "
+ << screen->logicalDotsPerInchX() << "DPI, DPR="
+ << screen->devicePixelRatio();
+ if (current)
+ str << "</i>";
+ str << "</li>";
+ }
+ str << "</ol></body></html>";
+ systemInfoTextBrowser->setHtml(systemInfo);
+}
+
+void WidgetGallery::helpOnCurrentWidget()
+{
+ // Skip over internal widgets
+ for (auto w = QApplication::widgetAt(QCursor::pos(screen())); w; w = w->parentWidget()) {
+ const QString name = w->objectName();
+ if (!name.isEmpty() && !name.startsWith(QLatin1String("qt_"))) {
+ launchHelp(w);
+ break;
+ }
+ }
+}
diff --git a/examples/xml/saxbookmarks/mainwindow.h b/examples/widgets/gallery/widgetgallery.h
index 20a11bb202..419c925190 100644
--- a/examples/xml/saxbookmarks/mainwindow.h
+++ b/examples/widgets/gallery/widgetgallery.h
@@ -1,6 +1,6 @@
/****************************************************************************
**
-** Copyright (C) 2016 The Qt Company Ltd.
+** Copyright (C) 2020 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
@@ -48,33 +48,43 @@
**
****************************************************************************/
-#ifndef MAINWINDOW_H
-#define MAINWINDOW_H
+#ifndef WIDGETGALLERY_H
+#define WIDGETGALLERY_H
-#include <QMainWindow>
+#include <QDialog>
QT_BEGIN_NAMESPACE
-class QTreeWidget;
+class QGroupBox;
+class QProgressBar;
+class QTabWidget;
+class QTextBrowser;
+class QToolBox;
QT_END_NAMESPACE
-class MainWindow : public QMainWindow
+class WidgetGallery : public QDialog
{
Q_OBJECT
public:
- MainWindow();
+ explicit WidgetGallery(QWidget *parent = nullptr);
+
+ void setVisible(bool visible) override;
+
+private slots:
+ void changeStyle(const QString &styleName);
+ void advanceProgressBar();
+ void helpOnCurrentWidget();
+ void updateSystemInfo();
-public slots:
- void open();
- void saveAs();
- void about();
-#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_CLIPBOARD)
- void onCustomContextMenuRequested(const QPoint &pos);
-#endif
private:
- void createMenus();
+ static QGroupBox *createButtonsGroupBox();
+ static QTabWidget *createItemViewTabWidget();
+ static QGroupBox *createSimpleInputWidgetsGroupBox();
+ QToolBox *createTextToolBox();
+ QProgressBar *createProgressBar();
- QTreeWidget *treeWidget;
+ QProgressBar *progressBar;
+ QTextBrowser *systemInfoTextBrowser;
};
-#endif
+#endif // WIDGETGALLERY_H
diff --git a/examples/widgets/graphicsview/boxes/3rdparty/fbm.c b/examples/widgets/graphicsview/boxes/3rdparty/fbm.c
deleted file mode 100644
index 3eebaabfba..0000000000
--- a/examples/widgets/graphicsview/boxes/3rdparty/fbm.c
+++ /dev/null
@@ -1,207 +0,0 @@
-/*****************************************************************
-
- 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;
- 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
deleted file mode 100644
index b8a4a99ae4..0000000000
--- a/examples/widgets/graphicsview/boxes/3rdparty/fbm.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*****************************************************************
-
- 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
deleted file mode 100644
index 327daeef54..0000000000
--- a/examples/widgets/graphicsview/boxes/basic.fsh
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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$
-**
-****************************************************************************/
-
-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
deleted file mode 100644
index 454e0bd903..0000000000
--- a/examples/widgets/graphicsview/boxes/basic.vsh
+++ /dev/null
@@ -1,70 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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$
-**
-****************************************************************************/
-
-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
deleted file mode 100644
index 601edd6883..0000000000
--- a/examples/widgets/graphicsview/boxes/boxes.pro
+++ /dev/null
@@ -1,27 +0,0 @@
-QT += opengl widgets
-requires(qtConfig(combobox))
-
-qtConfig(opengles.|angle|dynamicgl): error("This example requires Qt to be configured with -opengl desktop")
-
-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]/widgets/graphicsview/boxes
-INSTALLS += target
diff --git a/examples/widgets/graphicsview/boxes/boxes.qrc b/examples/widgets/graphicsview/boxes/boxes.qrc
deleted file mode 100644
index d27506dc5a..0000000000
--- a/examples/widgets/graphicsview/boxes/boxes.qrc
+++ /dev/null
@@ -1,25 +0,0 @@
-<!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
deleted file mode 100644
index 07c282eab9..0000000000
--- a/examples/widgets/graphicsview/boxes/cubemap_negx.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/cubemap_negy.jpg b/examples/widgets/graphicsview/boxes/cubemap_negy.jpg
deleted file mode 100644
index 46cd2f9cf3..0000000000
--- a/examples/widgets/graphicsview/boxes/cubemap_negy.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/cubemap_negz.jpg b/examples/widgets/graphicsview/boxes/cubemap_negz.jpg
deleted file mode 100644
index 40c01ddff3..0000000000
--- a/examples/widgets/graphicsview/boxes/cubemap_negz.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/cubemap_posx.jpg b/examples/widgets/graphicsview/boxes/cubemap_posx.jpg
deleted file mode 100644
index 0b42e8a1b1..0000000000
--- a/examples/widgets/graphicsview/boxes/cubemap_posx.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/cubemap_posy.jpg b/examples/widgets/graphicsview/boxes/cubemap_posy.jpg
deleted file mode 100644
index 2aca9b1e98..0000000000
--- a/examples/widgets/graphicsview/boxes/cubemap_posy.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/cubemap_posz.jpg b/examples/widgets/graphicsview/boxes/cubemap_posz.jpg
deleted file mode 100644
index 2e49173848..0000000000
--- a/examples/widgets/graphicsview/boxes/cubemap_posz.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/dotted.fsh b/examples/widgets/graphicsview/boxes/dotted.fsh
deleted file mode 100644
index 5cbf590e21..0000000000
--- a/examples/widgets/graphicsview/boxes/dotted.fsh
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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$
-**
-****************************************************************************/
-
-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
deleted file mode 100644
index 6758ad5770..0000000000
--- a/examples/widgets/graphicsview/boxes/fresnel.fsh
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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$
-**
-****************************************************************************/
-
-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
deleted file mode 100644
index 528d04e4d3..0000000000
--- a/examples/widgets/graphicsview/boxes/glass.fsh
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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$
-**
-****************************************************************************/
-
-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
deleted file mode 100644
index 91de336af3..0000000000
--- a/examples/widgets/graphicsview/boxes/glbuffers.cpp
+++ /dev/null
@@ -1,406 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 "glbuffers.h"
-
-void qgluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar)
-{
- const GLdouble ymax = zNear * tan(qDegreesToRadians(fovy) / 2.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()
-{
- 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, nullptr);
-
- 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, nullptr);
-
- 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, nullptr);
-
- 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;
- for (const 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, nullptr);
- ++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_width(width)
- , m_height(height)
-{
- 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 constexpr int perm[6][3] = {
- {2, 1, 0},
- {2, 1, 0},
- {0, 2, 1},
- {0, 2, 1},
- {0, 1, 2},
- {0, 1, 2},
- };
-
- static constexpr 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
deleted file mode 100644
index 4318e8ac24..0000000000
--- a/examples/widgets/graphicsview/boxes/glbuffers.h
+++ /dev/null
@@ -1,372 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 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 *>(nullptr)->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 = 0;
- bool m_failed = false;
-};
-
-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 = 0;
- GLuint m_depthBuffer = 0;
- int m_width, m_height;
- bool m_failed = false;
-};
-
-class GLTexture2D : public GLTexture
-{
-public:
- GLTexture2D(int width, int height);
- explicit GLTexture2D(const QString &fileName, int width = 0, int height = 0);
- void load(int width, int height, QRgb *data);
- void bind() override;
- void unbind() override;
-};
-
-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);
- void bind() override;
- void unbind() override;
-};
-
-class GLTextureCube : public GLTexture
-{
-public:
- GLTextureCube(int size);
- explicit GLTextureCube(const QStringList &fileNames, int size = 0);
- void load(int size, int face, QRgb *data);
- void bind() override;
- void unbind() override;
-};
-
-// 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();
- bool failed() const override { 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 = nullptr, int mode = GL_STATIC_DRAW)
- {
- 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 nullptr)
-
- 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 == nullptr);
- 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 = 0;
- int m_mode = 0;
- GLuint m_buffer = 0;
- bool m_failed = false;
-};
-
-template<class T>
-class GLIndexBuffer
-{
-public:
- GLIndexBuffer(int length, const T *data = nullptr, 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 nullptr)
-
- glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_buffer);
- GLvoid* buffer = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, GL_READ_WRITE);
- m_failed = (buffer == nullptr);
- 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
deleted file mode 100644
index ac89911046..0000000000
--- a/examples/widgets/graphicsview/boxes/glextensions.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 "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
deleted file mode 100644
index 685700d866..0000000000
--- a/examples/widgets/graphicsview/boxes/glextensions.h
+++ /dev/null
@@ -1,204 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 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 APIENTRY
-# define APIENTRY
-#endif
-#ifndef APIENTRYP
-# define APIENTRYP APIENTRY *
-#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
deleted file mode 100644
index e5c4f51514..0000000000
--- a/examples/widgets/graphicsview/boxes/gltrianglemesh.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 GLTRIANGLEMESH_H
-#define GLTRIANGLEMESH_H
-
-#include "glbuffers.h"
-#include "glextensions.h"
-
-#include <QtWidgets>
-#include <QtOpenGL>
-
-
-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
deleted file mode 100644
index 5dcde5d2b1..0000000000
--- a/examples/widgets/graphicsview/boxes/granite.fsh
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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$
-**
-****************************************************************************/
-
-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
deleted file mode 100644
index 2b3e6d3389..0000000000
--- a/examples/widgets/graphicsview/boxes/main.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 "glextensions.h"
-#include "scene.h"
-
-#include <QGLWidget>
-#include <QtWidgets>
-
-class GraphicsView : public QGraphicsView
-{
-public:
- GraphicsView()
- {
- setWindowTitle(tr("Boxes"));
- setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
- //setRenderHints(QPainter::SmoothPixmapTransform);
- }
-
-protected:
- void resizeEvent(QResizeEvent *event) override {
- 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(nullptr, "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(nullptr, "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(nullptr, "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(nullptr, "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
deleted file mode 100644
index c0b1980a67..0000000000
--- a/examples/widgets/graphicsview/boxes/marble.fsh
+++ /dev/null
@@ -1,80 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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$
-**
-****************************************************************************/
-
-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
deleted file mode 100644
index 50e20739b9..0000000000
--- a/examples/widgets/graphicsview/boxes/parameters.par
+++ /dev/null
@@ -1,5 +0,0 @@
-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
deleted file mode 100644
index 8d7fab052a..0000000000
--- a/examples/widgets/graphicsview/boxes/qt-logo.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/qt-logo.png b/examples/widgets/graphicsview/boxes/qt-logo.png
deleted file mode 100644
index 0b0b15480c..0000000000
--- a/examples/widgets/graphicsview/boxes/qt-logo.png
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/qtbox.cpp b/examples/widgets/graphicsview/boxes/qtbox.cpp
deleted file mode 100644
index 8713aac05d..0000000000
--- a/examples/widgets/graphicsview/boxes/qtbox.cpp
+++ /dev/null
@@ -1,470 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 "qtbox.h"
-
-constexpr qreal ROTATE_SPEED_X = 30.0 / 1000.0;
-constexpr qreal ROTATE_SPEED_Y = 20.0 / 1000.0;
-constexpr qreal ROTATE_SPEED_Z = 40.0 / 1000.0;
-constexpr int MAX_ITEM_SIZE = 512;
-constexpr int MIN_ITEM_SIZE = 16;
-
-//============================================================================//
-// ItemBase //
-//============================================================================//
-
-ItemBase::ItemBase(int size, int x, int y) : m_size(size), m_startTime(QTime::currentTime())
-{
- setFlag(QGraphicsItem::ItemIsMovable, true);
- setFlag(QGraphicsItem::ItemIsSelectable, true);
- setFlag(QGraphicsItem::ItemIsFocusable, true);
- setAcceptHoverEvents(true);
- setPos(x, y);
-}
-
-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;
-
- const QList<QGraphicsItem *> selected = scene->selectedItems();
- for (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;
-
- const QList<QGraphicsItem *> selected = scene->selectedItems();
- for (QGraphicsItem *item : selected) {
- ItemBase *itemBase = qgraphicsitem_cast<ItemBase *>(item);
- if (itemBase)
- delete itemBase;
- }
-}
-
-void ItemBase::growSelectedItems(QGraphicsScene *scene)
-{
- if (!scene)
- return;
-
- const QList<QGraphicsItem *> selected = scene->selectedItems();
- for (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;
-
- const QList<QGraphicsItem *> selected = scene->selectedItems();
- for (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 * qExp(-event->delta() / 600.0));
- m_size = qBound(MIN_ITEM_SIZE, m_size, MAX_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)
-{
- 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()
-{
- 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 == nullptr)
- 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(QRandomGenerator::global()->bounded(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 - qExp(-0.001 * ((dt + 3800) % 4000)));
- qreal r1 = 0.5 * m_size * (1.0 - qExp(-0.001 * ((dt + 0) % 4000)));
- qreal r2 = 0.5 * m_size * (1.0 - qExp(-0.001 * ((dt + 1800) % 4000)));
- qreal r3 = 0.5 * m_size * (1.0 - qExp(-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
deleted file mode 100644
index 84c8cb1d93..0000000000
--- a/examples/widgets/graphicsview/boxes/qtbox.h
+++ /dev/null
@@ -1,126 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 QTBOX_H
-#define QTBOX_H
-
-#include "glbuffers.h"
-
-#include <QtWidgets>
-#include <QVector3D>
-
-class ItemBase : public QGraphicsItem
-{
-public:
- enum { Type = UserType + 1 };
-
- ItemBase(int size, int x, int y);
- QRectF boundingRect() const override;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
-protected:
- virtual ItemBase *createNew(int size, int x, int y) = 0;
- void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override;
- void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
- void hoverMoveEvent(QGraphicsSceneHoverEvent *event) override;
- void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
- void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
- void keyPressEvent(QKeyEvent *event) override;
- void wheelEvent(QGraphicsSceneWheelEvent *event) override;
- int type() const override;
- 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 = false;
-};
-
-class QtBox : public ItemBase
-{
-public:
- QtBox(int size, int x, int y);
- virtual ~QtBox();
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
-protected:
- ItemBase *createNew(int size, int x, int y) override;
-private:
- QVector3D m_vertices[8];
- QVector3D m_texCoords[4];
- QVector3D m_normals[6];
- GLTexture *m_texture = nullptr;
-};
-
-class CircleItem : public ItemBase
-{
-public:
- CircleItem(int size, int x, int y);
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
-protected:
- ItemBase *createNew(int size, int x, int y) override;
-
- QColor m_color;
-};
-
-class SquareItem : public ItemBase
-{
-public:
- SquareItem(int size, int x, int y);
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
-protected:
- ItemBase *createNew(int size, int x, int y) override;
-
- QPixmap m_image;
-};
-
-#endif
diff --git a/examples/widgets/graphicsview/boxes/reflection.fsh b/examples/widgets/graphicsview/boxes/reflection.fsh
deleted file mode 100644
index 0f0a26476f..0000000000
--- a/examples/widgets/graphicsview/boxes/reflection.fsh
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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$
-**
-****************************************************************************/
-
-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
deleted file mode 100644
index 8ba2d36329..0000000000
--- a/examples/widgets/graphicsview/boxes/refraction.fsh
+++ /dev/null
@@ -1,79 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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$
-**
-****************************************************************************/
-
-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
deleted file mode 100644
index be96223b9f..0000000000
--- a/examples/widgets/graphicsview/boxes/roundedbox.cpp
+++ /dev/null
@@ -1,170 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 "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
deleted file mode 100644
index a1f15cd631..0000000000
--- a/examples/widgets/graphicsview/boxes/roundedbox.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 ROUNDEDBOX_H
-#define ROUNDEDBOX_H
-
-#include "glbuffers.h"
-#include "glextensions.h"
-#include "gltrianglemesh.h"
-
-#include <QVector2D>
-#include <QVector3D>
-
-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
- explicit 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
deleted file mode 100644
index b344f65561..0000000000
--- a/examples/widgets/graphicsview/boxes/scene.cpp
+++ /dev/null
@@ -1,1028 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 "scene.h"
-
-#include <QMatrix4x4>
-#include <QRandomGenerator>
-#include <QVector3D>
-#include <qmath.h>
-
-#include "3rdparty/fbm.h"
-
-//============================================================================//
-// 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, &QLineEdit::editingFinished, this, &ColorEdit::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, nullptr);
- dialog.setOption(QColorDialog::ShowAlphaChannel, true);
- 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, &QLineEdit::editingFinished, this, &FloatEdit::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 //
-//============================================================================//
-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);
-
- 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 nullptr;
- }
- 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, &TwoSidedGraphicsWidget::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(nullptr, 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, &QCheckBox::stateChanged, this, &RenderOptionsDialog::dynamicCubemapToggled);
- layout->addWidget(check, 0, 0, 1, 2);
- ++row;
-
- // Load all .par files
- // .par files have a simple syntax for specifying user adjustable uniform variables.
- const QList<QFileInfo> files = QDir(QStringLiteral(":/res/boxes/"))
- .entryInfoList({ QStringLiteral("*.par") },
- QDir::Files | QDir::Readable);
-
- for (const 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, &ColorEdit::colorChanged, this, &RenderOptionsDialog::setColorParameter);
- ++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, &FloatEdit::valueChanged, this, &RenderOptionsDialog::setFloatParameter);
- ++row;
- }
- }
- }
- file.close();
- }
- }
-
- layout->addWidget(new QLabel(tr("Texture:")));
- m_textureCombo = new QComboBox;
- connect(m_textureCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
- this, &RenderOptionsDialog::textureChanged);
- layout->addWidget(m_textureCombo);
- ++row;
-
- layout->addWidget(new QLabel(tr("Shader:")));
- m_shaderCombo = new QComboBox;
- connect(m_shaderCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
- this, &RenderOptionsDialog::shaderChanged);
- 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()
-{
- for (ParameterEdit *edit : qAsConst(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(nullptr, 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, &QAbstractButton::clicked, this, &ItemDialog::triggerNewQtBox);
-
- button = new QPushButton(tr("Add circle"));
- layout->addWidget(button);
- connect(button, &QAbstractButton::clicked, this, &ItemDialog::triggerNewCircleItem);
-
- button = new QPushButton(tr("Add square"));
- layout->addWidget(button);
- connect(button, &QAbstractButton::clicked, this, &ItemDialog::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(nullptr)
- , m_vertexShader(nullptr)
- , m_environmentShader(nullptr)
- , m_environmentProgram(nullptr)
-{
- 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, &RenderOptionsDialog::dynamicCubemapToggled, this, &Scene::toggleDynamicCubemap);
- connect(m_renderOptions, &RenderOptionsDialog::colorParameterChanged, this, &Scene::setColorParameter);
- connect(m_renderOptions, &RenderOptionsDialog::floatParameterChanged, this, &Scene::setFloatParameter);
- connect(m_renderOptions, &RenderOptionsDialog::textureChanged, this, &Scene::setTexture);
- connect(m_renderOptions, &RenderOptionsDialog::shaderChanged, this, &Scene::setShader);
-
- m_itemDialog = new ItemDialog;
- connect(m_itemDialog, &ItemDialog::newItemTriggered, this, &Scene::newItem);
-
- TwoSidedGraphicsWidget *twoSided = new TwoSidedGraphicsWidget(this);
- twoSided->setWidget(0, m_renderOptions);
- twoSided->setWidget(1, m_itemDialog);
-
- connect(m_renderOptions, &RenderOptionsDialog::doubleClicked, twoSided, &TwoSidedGraphicsWidget::flip);
- connect(m_itemDialog, &ItemDialog::doubleClicked, twoSided, &TwoSidedGraphicsWidget::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, &QTimer::timeout, this, [this](){ update(); });
- m_timer->start();
-}
-
-Scene::~Scene()
-{
- delete m_box;
- qDeleteAll(m_textures);
- delete m_mainCubemap;
- qDeleteAll(m_programs);
- delete m_vertexShader;
- qDeleteAll(m_fragmentShaders);
- qDeleteAll(m_cubemaps);
- delete m_environmentShader;
- 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);
- QVector<QRgb> data(NOISE_SIZE * NOISE_SIZE * NOISE_SIZE, QRgb(0));
- QRgb *p = data.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.data());
-
- m_mainCubemap = new GLRenderTargetCube(512);
-
- QList<QFileInfo> files;
-
- // Load all .png files as textures
- m_currentTexture = 0;
- files = QDir(":/res/boxes/").entryInfoList({ QStringLiteral("*.png") }, QDir::Files | QDir::Readable);
-
- for (const QFileInfo &file : qAsConst(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;
- files = QDir(":/res/boxes/").entryInfoList({ QStringLiteral("*.fsh") }, QDir::Files | QDir::Readable);
- for (const QFileInfo &file : qAsConst(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)) : nullptr);
- 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 float *data = m.constData();
- for (int index = 0; index < 16; ++index)
- mat[index] = data[index];
- glLoadMatrixf(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());
- glMultMatrixf(m.constData());
-
- 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());
- glMultMatrixf(m.constData());
-
- 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;
-
- const float eachAngle = 2 * M_PI / m_cubemaps.size();
- for (int i = m_frame % N; i < m_cubemaps.size(); i += N) {
- if (0 == m_cubemaps[i])
- continue;
-
- float angle = i * eachAngle;
-
- center = m_trackBalls[1].rotation().rotatedVector(QVector3D(std::cos(angle), std::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 * std::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().conjugated());
- event->accept();
- } else {
- m_trackBalls[0].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- }
-
- if (event->buttons() & Qt::RightButton) {
- m_trackBalls[1].move(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- event->accept();
- } else {
- m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- }
-
- 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().conjugated());
- event->accept();
- }
-
- if (event->buttons() & Qt::RightButton) {
- m_trackBalls[1].push(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- 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().conjugated());
- event->accept();
- }
-
- if (event->button() == Qt::RightButton) {
- m_trackBalls[1].release(pixelPosToViewPos(event->scenePos()), m_trackBalls[2].rotation().conjugated());
- 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
- for (QGLShaderProgram *program : qAsConst(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
- for (QGLShaderProgram *program : qAsConst(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, QRandomGenerator::global()->bounded(size.width() - 64) + 32,
- QRandomGenerator::global()->bounded(size.height() - 64) + 32));
- break;
- case ItemDialog::CircleItem:
- addItem(new CircleItem(64, QRandomGenerator::global()->bounded(size.width() - 64) + 32,
- QRandomGenerator::global()->bounded(size.height() - 64) + 32));
- break;
- case ItemDialog::SquareItem:
- addItem(new SquareItem(64, QRandomGenerator::global()->bounded(size.width() - 64) + 32,
- QRandomGenerator::global()->bounded(size.height() - 64) + 32));
- break;
- default:
- break;
- }
-}
diff --git a/examples/widgets/graphicsview/boxes/scene.h b/examples/widgets/graphicsview/boxes/scene.h
deleted file mode 100644
index 5d65dc71e2..0000000000
--- a/examples/widgets/graphicsview/boxes/scene.h
+++ /dev/null
@@ -1,247 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 SCENE_H
-#define SCENE_H
-
-#include "glbuffers.h"
-#include "glextensions.h"
-#include "gltrianglemesh.h"
-#include "qtbox.h"
-#include "roundedbox.h"
-#include "trackball.h"
-
-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;}
- void emitChange() override { emit colorChanged(m_color, m_id); }
-public slots:
- void editDone();
-signals:
- void colorChanged(QRgb color, int id);
-protected:
- void mousePressEvent(QMouseEvent *event) override;
- 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;}
- void emitChange() override { 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(nullptr, Qt::Window) {}
-protected:
- QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
- void resizeEvent(QGraphicsSceneResizeEvent *event) override;
- void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
-};
-
-class TwoSidedGraphicsWidget : public QObject
-{
- Q_OBJECT
-public:
- using QObject::QObject;
- void setWidget(int index, QWidget *widget);
- QWidget *widget(int index);
-public slots:
- void flip();
-protected slots:
- void animateFlip();
-private:
- GraphicsWidget *m_proxyWidgets[2] = {nullptr, nullptr};
- int m_current = 0;
- int m_angle = 0; // angle in degrees
- int m_delta = 0;
-};
-
-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:
- void mouseDoubleClickEvent(QMouseEvent *event) override;
-
- 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:
- void mouseDoubleClickEvent(QMouseEvent *event) override;
-};
-
-class Scene : public QGraphicsScene
-{
- Q_OBJECT
-public:
- Scene(int width, int height, int maxTextureSize);
- ~Scene();
- void drawBackground(QPainter *painter, const QRectF &rect) override;
-
-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();
-
- void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
- void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
- void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
- void wheelEvent(QGraphicsSceneWheelEvent * event) override;
-private:
- void initGL();
- QPointF pixelPosToViewPos(const QPointF& p);
-
- QTime m_time; // ### Qt 6: remove (unused)
- 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
deleted file mode 100644
index 41cfda6b23..0000000000
--- a/examples/widgets/graphicsview/boxes/smiley.png
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/square.jpg b/examples/widgets/graphicsview/boxes/square.jpg
deleted file mode 100644
index 03f53bd530..0000000000
--- a/examples/widgets/graphicsview/boxes/square.jpg
+++ /dev/null
Binary files differ
diff --git a/examples/widgets/graphicsview/boxes/trackball.cpp b/examples/widgets/graphicsview/boxes/trackball.cpp
deleted file mode 100644
index b9dfc1fc7f..0000000000
--- a/examples/widgets/graphicsview/boxes/trackball.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 "trackball.h"
-#include "scene.h"
-
-//============================================================================//
-// TrackBall //
-//============================================================================//
-
-TrackBall::TrackBall(TrackMode mode)
- : TrackBall(0, QVector3D(0, 1, 0), mode)
-{
-}
-
-TrackBall::TrackBall(float angularVelocity, const QVector3D& axis, TrackMode mode)
- : m_axis(axis)
- , m_angularVelocity(angularVelocity)
- , m_mode(mode)
-{}
-
-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);
- const float angleDelta = qRadiansToDegrees(float(delta.length()));
- m_angularVelocity = angleDelta / msecs;
- m_axis = QVector3D(-delta.dy(), delta.dx(), 0.0f).normalized();
- m_axis = transformation.rotatedVector(m_axis);
- m_rotation = QQuaternion::fromAxisAndAngle(m_axis, angleDelta) * 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(std::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(std::sqrt(sqrZ));
- else
- currentPos3D.normalize();
-
- m_axis = QVector3D::crossProduct(lastPos3D, currentPos3D);
- float angle = qRadiansToDegrees(std::asin(m_axis.length()));
-
- 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
deleted file mode 100644
index af90e4d842..0000000000
--- a/examples/widgets/graphicsview/boxes/trackball.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 TRACKBALL_H
-#define TRACKBALL_H
-
-#include <QQuaternion>
-#include <QTime>
-#include <QVector3D>
-
-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 = QVector3D(0, 1, 0);
- float m_angularVelocity = 0;
-
- QPointF m_lastPos;
- QTime m_lastTime = QTime::currentTime();
- TrackMode m_mode;
- bool m_paused = false;
- bool m_pressed = false;
-};
-
-#endif
diff --git a/examples/widgets/graphicsview/boxes/wood.fsh b/examples/widgets/graphicsview/boxes/wood.fsh
deleted file mode 100644
index fbb5195f3a..0000000000
--- a/examples/widgets/graphicsview/boxes/wood.fsh
+++ /dev/null
@@ -1,79 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the demonstration applications of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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$
-**
-****************************************************************************/
-
-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.pro b/examples/widgets/graphicsview/chip/chip.pro
index a46f07ce35..508928d026 100644
--- a/examples/widgets/graphicsview/chip/chip.pro
+++ b/examples/widgets/graphicsview/chip/chip.pro
@@ -6,7 +6,6 @@ SOURCES += mainwindow.cpp view.cpp chip.cpp
QT += widgets
qtHaveModule(printsupport): QT += printsupport
-qtHaveModule(opengl): QT += opengl
build_all:!build_pass {
CONFIG -= build_all
diff --git a/examples/widgets/graphicsview/chip/view.cpp b/examples/widgets/graphicsview/chip/view.cpp
index 21998dc2df..77a6310778 100644
--- a/examples/widgets/graphicsview/chip/view.cpp
+++ b/examples/widgets/graphicsview/chip/view.cpp
@@ -57,11 +57,7 @@
#include <QPrintDialog>
#endif
#endif
-#ifndef QT_NO_OPENGL
-#include <QtOpenGL>
-#else
#include <QtWidgets>
-#endif
#include <QtMath>
#if QT_CONFIG(wheelevent)
@@ -156,14 +152,6 @@ View::View(const QString &name, QWidget *parent)
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")));
@@ -179,7 +167,6 @@ View::View(const QString &name, QWidget *parent)
labelLayout->addWidget(dragModeButton);
labelLayout->addStretch();
labelLayout->addWidget(antialiasButton);
- labelLayout->addWidget(openGlButton);
labelLayout->addWidget(printButton);
QGridLayout *topLayout = new QGridLayout;
@@ -200,7 +187,6 @@ View::View(const QString &name, QWidget *parent)
connect(selectModeButton, &QAbstractButton::toggled, this, &View::togglePointerMode);
connect(dragModeButton, &QAbstractButton::toggled, this, &View::togglePointerMode);
connect(antialiasButton, &QAbstractButton::toggled, this, &View::toggleAntialiasing);
- connect(openGlButton, &QAbstractButton::toggled, this, &View::toggleOpenGL);
connect(rotateLeftIcon, &QAbstractButton::clicked, this, &View::rotateLeft);
connect(rotateRightIcon, &QAbstractButton::clicked, this, &View::rotateRight);
connect(zoomInIcon, &QAbstractButton::clicked, this, &View::zoomIn);
@@ -250,13 +236,6 @@ void View::togglePointerMode()
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());
diff --git a/examples/widgets/graphicsview/chip/view.h b/examples/widgets/graphicsview/chip/view.h
index ea7bd414f5..b780702c34 100644
--- a/examples/widgets/graphicsview/chip/view.h
+++ b/examples/widgets/graphicsview/chip/view.h
@@ -94,7 +94,6 @@ private slots:
void setResetButtonEnabled();
void setupMatrix();
void togglePointerMode();
- void toggleOpenGL();
void toggleAntialiasing();
void print();
void rotateLeft();
@@ -106,7 +105,6 @@ private:
QLabel *label2;
QToolButton *selectModeButton;
QToolButton *dragModeButton;
- QToolButton *openGlButton;
QToolButton *antialiasButton;
QToolButton *printButton;
QToolButton *resetButton;
diff --git a/examples/widgets/graphicsview/embeddeddialogs/customproxy.h b/examples/widgets/graphicsview/embeddeddialogs/customproxy.h
index d7df2b7b4b..5aa0250a29 100644
--- a/examples/widgets/graphicsview/embeddeddialogs/customproxy.h
+++ b/examples/widgets/graphicsview/embeddeddialogs/customproxy.h
@@ -59,7 +59,7 @@ class CustomProxy : public QGraphicsProxyWidget
Q_OBJECT
public:
- explicit CustomProxy(QGraphicsItem *parent = nullptr, Qt::WindowFlags wFlags = nullptr);
+ explicit CustomProxy(QGraphicsItem *parent = nullptr, Qt::WindowFlags wFlags = { });
QRectF boundingRect() const override;
void paintWindowFrame(QPainter *painter, const QStyleOptionGraphicsItem *option,
diff --git a/examples/widgets/graphicsview/graphicsview.pro b/examples/widgets/graphicsview/graphicsview.pro
index b9bef70a0e..d591450559 100644
--- a/examples/widgets/graphicsview/graphicsview.pro
+++ b/examples/widgets/graphicsview/graphicsview.pro
@@ -14,7 +14,3 @@ SUBDIRS = \
weatheranchorlayout
contains(DEFINES, QT_NO_CURSOR)|!qtConfig(draganddrop): SUBDIRS -= dragdroprobot
-
-qtHaveModule(opengl):!qtConfig(opengles.):!qtConfig(dynamicgl) {
- SUBDIRS += boxes
-}
diff --git a/examples/widgets/graphicsview/padnavigator/padnavigator.cpp b/examples/widgets/graphicsview/padnavigator/padnavigator.cpp
index b9ce2a47ca..dbf89dd318 100644
--- a/examples/widgets/graphicsview/padnavigator/padnavigator.cpp
+++ b/examples/widgets/graphicsview/padnavigator/padnavigator.cpp
@@ -142,24 +142,16 @@ PadNavigator::PadNavigator(const QSize &size, QWidget *parent)
// 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]
diff --git a/examples/widgets/layouts/flowlayout/flowlayout.cpp b/examples/widgets/layouts/flowlayout/flowlayout.cpp
index 5c59ae025c..9a488557cf 100644
--- a/examples/widgets/layouts/flowlayout/flowlayout.cpp
+++ b/examples/widgets/layouts/flowlayout/flowlayout.cpp
@@ -123,7 +123,7 @@ QLayoutItem *FlowLayout::takeAt(int index)
//! [6]
Qt::Orientations FlowLayout::expandingDirections() const
{
- return 0;
+ return { };
}
//! [6]
diff --git a/examples/widgets/mainwindows/mainwindow/colorswatch.h b/examples/widgets/mainwindows/mainwindow/colorswatch.h
index 7f73e46f31..2bd9fd2891 100644
--- a/examples/widgets/mainwindows/mainwindow/colorswatch.h
+++ b/examples/widgets/mainwindows/mainwindow/colorswatch.h
@@ -62,7 +62,7 @@ class ColorSwatch : public QDockWidget
Q_OBJECT
public:
- explicit ColorSwatch(const QString &colorName, QMainWindow *parent = nullptr, Qt::WindowFlags flags = 0);
+ explicit ColorSwatch(const QString &colorName, QMainWindow *parent = nullptr, Qt::WindowFlags flags = { });
void setCustomSizeHint(const QSize &size);
QMenu *colorSwatchMenu() const { return menu; }
diff --git a/examples/widgets/mainwindows/mainwindow/mainwindow.h b/examples/widgets/mainwindows/mainwindow/mainwindow.h
index a2c9d30ded..3ce9732763 100644
--- a/examples/widgets/mainwindows/mainwindow/mainwindow.h
+++ b/examples/widgets/mainwindows/mainwindow/mainwindow.h
@@ -65,7 +65,7 @@ public:
explicit MainWindow(const CustomSizeHintMap &customSizeHints,
QWidget *parent = nullptr,
- Qt::WindowFlags flags = 0);
+ Qt::WindowFlags flags = { });
public slots:
void actionTriggered(QAction *action);
diff --git a/examples/widgets/painting/shared/arthurwidgets.cpp b/examples/widgets/painting/shared/arthurwidgets.cpp
index 40d712c9e3..c7c851270b 100644
--- a/examples/widgets/painting/shared/arthurwidgets.cpp
+++ b/examples/widgets/painting/shared/arthurwidgets.cpp
@@ -63,7 +63,9 @@
#include <QOffscreenSurface>
#include <QOpenGLContext>
#include <QOpenGLPaintDevice>
-#include <QOpenGLWindow>
+#if QT_CONFIG(opengl)
+#include <QtOpenGL/QOpenGLWindow>
+#endif
extern QPixmap cached(const QString &img);
diff --git a/examples/widgets/painting/shared/hoverpoints.cpp b/examples/widgets/painting/shared/hoverpoints.cpp
index 2bf3963e9e..f834f315f9 100644
--- a/examples/widgets/painting/shared/hoverpoints.cpp
+++ b/examples/widgets/painting/shared/hoverpoints.cpp
@@ -53,6 +53,10 @@
#include <algorithm>
+#if QT_CONFIG(opengl)
+#include <QtOpenGL/QOpenGLWindow>
+#endif
+
#define printf
HoverPoints::HoverPoints(QWidget *widget, PointShape shape)
diff --git a/examples/widgets/painting/shared/shared.pri b/examples/widgets/painting/shared/shared.pri
index cb08b00348..7e2b4df8cb 100644
--- a/examples/widgets/painting/shared/shared.pri
+++ b/examples/widgets/painting/shared/shared.pri
@@ -1,6 +1,7 @@
INCLUDEPATH += $$PWD
qtConfig(opengl) {
+ QT += opengl
SOURCES += $$PWD/fbopaintdevice.cpp
HEADERS += $$PWD/fbopaintdevice.h
}
diff --git a/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp b/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp
index ea3cb00a02..6398098eee 100644
--- a/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp
+++ b/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp
@@ -286,7 +286,7 @@ void RegularExpressionDialog::refresh()
setResultUiEnabled(true);
- QRegularExpression::MatchType matchType = matchTypeComboBox->currentData().value<QRegularExpression::MatchType>();
+ QRegularExpression::MatchType matchType = qvariant_cast<QRegularExpression::MatchType>(matchTypeComboBox->currentData());
QRegularExpression::PatternOptions patternOptions = QRegularExpression::NoPatternOption;
QRegularExpression::MatchOptions matchOptions = QRegularExpression::NoMatchOption;
diff --git a/examples/widgets/widgets.pro b/examples/widgets/widgets.pro
index d975ea8307..99e1c71594 100644
--- a/examples/widgets/widgets.pro
+++ b/examples/widgets/widgets.pro
@@ -9,6 +9,7 @@ SUBDIRS = \
dialogs \
draganddrop \
effects \
+ gallery \
gestures \
graphicsview \
itemviews \
diff --git a/examples/widgets/widgets/charactermap/mainwindow.cpp b/examples/widgets/widgets/charactermap/mainwindow.cpp
index b0f9705c21..702b50156b 100644
--- a/examples/widgets/widgets/charactermap/mainwindow.cpp
+++ b/examples/widgets/widgets/charactermap/mainwindow.cpp
@@ -201,7 +201,7 @@ void MainWindow::findStyles(const QFont &font)
void MainWindow::filterChanged(int f)
{
const QFontComboBox::FontFilter filter =
- filterCombo->itemData(f).value<QFontComboBox::FontFilter>();
+ qvariant_cast<QFontComboBox::FontFilter>(filterCombo->itemData(f));
fontCombo->setFontFilters(filter);
statusBar()->showMessage(tr("%n font(s) found", nullptr, fontCombo->count()));
}
diff --git a/examples/widgets/widgets/icons/mainwindow.cpp b/examples/widgets/widgets/icons/mainwindow.cpp
index 8e61260041..4f990f7320 100644
--- a/examples/widgets/widgets/icons/mainwindow.cpp
+++ b/examples/widgets/widgets/icons/mainwindow.cpp
@@ -361,7 +361,7 @@ QWidget *MainWindow::createImagesGroupBox()
QVBoxLayout *layout = new QVBoxLayout(imagesGroupBox);
layout->addWidget(imagesTable);
return imagesGroupBox;
-//! [25]
+//! [24]
}
//! [26]
diff --git a/examples/widgets/widgets/shapedclock/shapedclock.cpp b/examples/widgets/widgets/shapedclock/shapedclock.cpp
index 3c78f4da89..673d1a218f 100644
--- a/examples/widgets/widgets/shapedclock/shapedclock.cpp
+++ b/examples/widgets/widgets/shapedclock/shapedclock.cpp
@@ -61,6 +61,7 @@
ShapedClock::ShapedClock(QWidget *parent)
: QWidget(parent, Qt::FramelessWindowHint | Qt::WindowSystemMenuHint)
{
+ setAttribute(Qt::WA_TranslucentBackground);
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, QOverload<>::of(&ShapedClock::update));
timer->start(1000);
@@ -123,6 +124,10 @@ void ShapedClock::paintEvent(QPaintEvent *)
painter.scale(side / 200.0, side / 200.0);
painter.setPen(Qt::NoPen);
+ painter.setBrush(palette().window());
+ painter.drawEllipse(QPoint(0, 0), 98, 98);
+
+ painter.setPen(Qt::NoPen);
painter.setBrush(hourColor);
painter.save();
@@ -168,6 +173,6 @@ void ShapedClock::resizeEvent(QResizeEvent * /* event */)
//! [5]
QSize ShapedClock::sizeHint() const
{
- return QSize(100, 100);
+ return QSize(200, 200);
}
//! [5]
diff --git a/examples/widgets/widgets/styles/main.cpp b/examples/widgets/widgets/styles/main.cpp
index d340719984..471589d3ad 100644
--- a/examples/widgets/widgets/styles/main.cpp
+++ b/examples/widgets/widgets/styles/main.cpp
@@ -50,12 +50,15 @@
#include <QApplication>
+#include "norwegianwoodstyle.h"
#include "widgetgallery.h"
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(styles);
+ QApplication::setStyle(new NorwegianWoodStyle);
+
QApplication app(argc, argv);
WidgetGallery gallery;
gallery.show();
diff --git a/examples/widgets/widgets/styles/norwegianwoodstyle.cpp b/examples/widgets/widgets/styles/norwegianwoodstyle.cpp
index 0f614a2e9a..31150cd994 100644
--- a/examples/widgets/widgets/styles/norwegianwoodstyle.cpp
+++ b/examples/widgets/widgets/styles/norwegianwoodstyle.cpp
@@ -58,45 +58,52 @@
NorwegianWoodStyle::NorwegianWoodStyle() :
QProxyStyle(QStyleFactory::create("windows"))
{
+ setObjectName("NorwegianWood");
}
//! [0]
-void NorwegianWoodStyle::polish(QPalette &palette)
+QPalette NorwegianWoodStyle::standardPalette() const
{
- QColor brown(212, 140, 95);
- QColor beige(236, 182, 120);
- QColor slightlyOpaqueBlack(0, 0, 0, 63);
-
- QImage backgroundImage(":/images/woodbackground.png");
- QImage buttonImage(":/images/woodbutton.png");
- QImage midImage = buttonImage.convertToFormat(QImage::Format_RGB32);
-
- QPainter painter;
- painter.begin(&midImage);
- painter.setPen(Qt::NoPen);
- painter.fillRect(midImage.rect(), slightlyOpaqueBlack);
- painter.end();
-//! [0]
+ if (!m_standardPalette.isBrushSet(QPalette::Disabled, QPalette::Mid)) {
+ QColor brown(212, 140, 95);
+ QColor beige(236, 182, 120);
+ QColor slightlyOpaqueBlack(0, 0, 0, 63);
+
+ QImage backgroundImage(":/images/woodbackground.png");
+ QImage buttonImage(":/images/woodbutton.png");
+ QImage midImage = buttonImage.convertToFormat(QImage::Format_RGB32);
+
+ QPainter painter;
+ painter.begin(&midImage);
+ painter.setPen(Qt::NoPen);
+ painter.fillRect(midImage.rect(), slightlyOpaqueBlack);
+ painter.end();
+ //! [0]
+
+ //! [1]
+ QPalette palette(brown);
+
+ palette.setBrush(QPalette::BrightText, Qt::white);
+ palette.setBrush(QPalette::Base, beige);
+ palette.setBrush(QPalette::Highlight, Qt::darkGreen);
+ setTexture(palette, QPalette::Button, buttonImage);
+ setTexture(palette, QPalette::Mid, midImage);
+ setTexture(palette, QPalette::Window, backgroundImage);
+
+ QBrush brush = palette.window();
+ brush.setColor(brush.color().darker());
+
+ palette.setBrush(QPalette::Disabled, QPalette::WindowText, brush);
+ palette.setBrush(QPalette::Disabled, QPalette::Text, brush);
+ palette.setBrush(QPalette::Disabled, QPalette::ButtonText, brush);
+ palette.setBrush(QPalette::Disabled, QPalette::Base, brush);
+ palette.setBrush(QPalette::Disabled, QPalette::Button, brush);
+ palette.setBrush(QPalette::Disabled, QPalette::Mid, brush);
+
+ m_standardPalette = palette;
+ }
-//! [1]
- palette = QPalette(brown);
-
- palette.setBrush(QPalette::BrightText, Qt::white);
- palette.setBrush(QPalette::Base, beige);
- palette.setBrush(QPalette::Highlight, Qt::darkGreen);
- setTexture(palette, QPalette::Button, buttonImage);
- setTexture(palette, QPalette::Mid, midImage);
- setTexture(palette, QPalette::Window, backgroundImage);
-
- QBrush brush = palette.window();
- brush.setColor(brush.color().darker());
-
- palette.setBrush(QPalette::Disabled, QPalette::WindowText, brush);
- palette.setBrush(QPalette::Disabled, QPalette::Text, brush);
- palette.setBrush(QPalette::Disabled, QPalette::ButtonText, brush);
- palette.setBrush(QPalette::Disabled, QPalette::Base, brush);
- palette.setBrush(QPalette::Disabled, QPalette::Button, brush);
- palette.setBrush(QPalette::Disabled, QPalette::Mid, brush);
+ return m_standardPalette;
}
//! [1]
diff --git a/examples/widgets/widgets/styles/norwegianwoodstyle.h b/examples/widgets/widgets/styles/norwegianwoodstyle.h
index 5a1783eb4d..62ca502d05 100644
--- a/examples/widgets/widgets/styles/norwegianwoodstyle.h
+++ b/examples/widgets/widgets/styles/norwegianwoodstyle.h
@@ -66,7 +66,8 @@ class NorwegianWoodStyle : public QProxyStyle
public:
NorwegianWoodStyle();
- void polish(QPalette &palette) override;
+ QPalette standardPalette() const override;
+
void polish(QWidget *widget) override;
void unpolish(QWidget *widget) override;
int pixelMetric(PixelMetric metric, const QStyleOption *option,
@@ -82,6 +83,7 @@ private:
static void setTexture(QPalette &palette, QPalette::ColorRole role,
const QImage &image);
static QPainterPath roundRectPath(const QRect &rect);
+ mutable QPalette m_standardPalette;
};
//! [0]
diff --git a/examples/widgets/widgets/styles/widgetgallery.cpp b/examples/widgets/widgets/styles/widgetgallery.cpp
index fd8f0ec2d1..bf8e93feb4 100644
--- a/examples/widgets/widgets/styles/widgetgallery.cpp
+++ b/examples/widgets/widgets/styles/widgetgallery.cpp
@@ -65,6 +65,7 @@
#include <QRadioButton>
#include <QScrollBar>
#include <QSpinBox>
+#include <QStyle>
#include <QStyleFactory>
#include <QTableWidget>
#include <QTextEdit>
@@ -74,11 +75,17 @@
WidgetGallery::WidgetGallery(QWidget *parent)
: QDialog(parent)
{
- originalPalette = QApplication::palette();
-
styleComboBox = new QComboBox;
- styleComboBox->addItem("NorwegianWood");
- styleComboBox->addItems(QStyleFactory::keys());
+ const QString defaultStyleName = QApplication::style()->objectName();
+ QStringList styleNames = QStyleFactory::keys();
+ styleNames.append("NorwegianWood");
+ for (int i = 1, size = styleNames.size(); i < size; ++i) {
+ if (defaultStyleName.compare(styleNames.at(i), Qt::CaseInsensitive) == 0) {
+ styleNames.swapItemsAt(0, i);
+ break;
+ }
+ }
+ styleComboBox->addItems(styleNames);
styleLabel = new QLabel(tr("&Style:"));
styleLabel->setBuddy(styleComboBox);
@@ -134,7 +141,7 @@ WidgetGallery::WidgetGallery(QWidget *parent)
setLayout(mainLayout);
setWindowTitle(tr("Styles"));
- changeStyle("NorwegianWood");
+ styleChanged();
}
//! [4]
@@ -142,12 +149,10 @@ WidgetGallery::WidgetGallery(QWidget *parent)
void WidgetGallery::changeStyle(const QString &styleName)
//! [5] //! [6]
{
- if (styleName == "NorwegianWood") {
+ if (styleName == "NorwegianWood")
QApplication::setStyle(new NorwegianWoodStyle);
- } else {
+ else
QApplication::setStyle(QStyleFactory::create(styleName));
- }
- changePalette();
}
//! [6]
@@ -155,13 +160,30 @@ void WidgetGallery::changeStyle(const QString &styleName)
void WidgetGallery::changePalette()
//! [7] //! [8]
{
- if (useStylePaletteCheckBox->isChecked())
- QApplication::setPalette(QApplication::style()->standardPalette());
- else
- QApplication::setPalette(originalPalette);
+ QApplication::setPalette(useStylePaletteCheckBox->isChecked() ?
+ QApplication::style()->standardPalette() : QPalette());
}
//! [8]
+void WidgetGallery::changeEvent(QEvent *event)
+{
+ if (event->type() == QEvent::StyleChange)
+ styleChanged();
+}
+
+void WidgetGallery::styleChanged()
+{
+ auto styleName = QApplication::style()->objectName();
+ for (int i = 0; i < styleComboBox->count(); ++i) {
+ if (QString::compare(styleComboBox->itemText(i), styleName, Qt::CaseInsensitive) == 0) {
+ styleComboBox->setCurrentIndex(i);
+ break;
+ }
+ }
+
+ changePalette();
+}
+
//! [9]
void WidgetGallery::advanceProgressBar()
//! [9] //! [10]
diff --git a/examples/widgets/widgets/styles/widgetgallery.h b/examples/widgets/widgets/styles/widgetgallery.h
index 9ee65c21c4..8c4c880536 100644
--- a/examples/widgets/widgets/styles/widgetgallery.h
+++ b/examples/widgets/widgets/styles/widgetgallery.h
@@ -80,8 +80,12 @@ class WidgetGallery : public QDialog
public:
WidgetGallery(QWidget *parent = nullptr);
+protected:
+ void changeEvent(QEvent *) override;
+
private slots:
void changeStyle(const QString &styleName);
+ void styleChanged();
void changePalette();
void advanceProgressBar();
@@ -92,8 +96,6 @@ private:
void createBottomRightGroupBox();
void createProgressBar();
- QPalette originalPalette;
-
QLabel *styleLabel;
QComboBox *styleComboBox;
QCheckBox *useStylePaletteCheckBox;
diff --git a/examples/widgets/widgets/tablet/mainwindow.cpp b/examples/widgets/widgets/tablet/mainwindow.cpp
index 8bcb9ada63..c5b631ee44 100644
--- a/examples/widgets/widgets/tablet/mainwindow.cpp
+++ b/examples/widgets/widgets/tablet/mainwindow.cpp
@@ -85,21 +85,21 @@ void MainWindow::setBrushColor()
//! [2]
void MainWindow::setAlphaValuator(QAction *action)
{
- m_canvas->setAlphaChannelValuator(action->data().value<TabletCanvas::Valuator>());
+ m_canvas->setAlphaChannelValuator(qvariant_cast<TabletCanvas::Valuator>(action->data()));
}
//! [2]
//! [3]
void MainWindow::setLineWidthValuator(QAction *action)
{
- m_canvas->setLineWidthType(action->data().value<TabletCanvas::Valuator>());
+ m_canvas->setLineWidthType(qvariant_cast<TabletCanvas::Valuator>(action->data()));
}
//! [3]
//! [4]
void MainWindow::setSaturationValuator(QAction *action)
{
- m_canvas->setColorSaturationValuator(action->data().value<TabletCanvas::Valuator>());
+ m_canvas->setColorSaturationValuator(qvariant_cast<TabletCanvas::Valuator>(action->data()));
}
//! [4]
diff --git a/examples/widgets/widgets/validators/localeselector.cpp b/examples/widgets/widgets/validators/localeselector.cpp
index 1382da0cc9..3dcd04d9ff 100644
--- a/examples/widgets/widgets/validators/localeselector.cpp
+++ b/examples/widgets/widgets/validators/localeselector.cpp
@@ -90,6 +90,6 @@ void LocaleSelector::emitLocaleSelected(int index)
QVariant v = itemData(index);
if (!v.isValid())
return;
- const QLocale l = v.value<QLocale>();
+ const QLocale l = qvariant_cast<QLocale>(v);
emit localeSelected(l);
}
diff --git a/examples/xml/dombookmarks/xbeltree.cpp b/examples/xml/dombookmarks/xbeltree.cpp
index d90cdc03b4..76ea5fb2bb 100644
--- a/examples/xml/dombookmarks/xbeltree.cpp
+++ b/examples/xml/dombookmarks/xbeltree.cpp
@@ -153,7 +153,7 @@ bool XbelTree::write(QIODevice *device) const
void XbelTree::updateDomElement(const QTreeWidgetItem *item, int column)
{
- QDomElement element = item->data(0, DomElementRole).value<QDomElement>();
+ QDomElement element = qvariant_cast<QDomElement>(item->data(0, DomElementRole));
if (!element.isNull()) {
if (column == 0) {
QDomElement oldTitleElement = element.firstChildElement(titleElement());
diff --git a/examples/xml/saxbookmarks/CMakeLists.txt b/examples/xml/saxbookmarks/CMakeLists.txt
deleted file mode 100644
index 40244e0e73..0000000000
--- a/examples/xml/saxbookmarks/CMakeLists.txt
+++ /dev/null
@@ -1,31 +0,0 @@
-# Generated from saxbookmarks.pro.
-
-cmake_minimum_required(VERSION 3.14)
-project(saxbookmarks LANGUAGES CXX)
-
-set(CMAKE_INCLUDE_CURRENT_DIR ON)
-
-set(CMAKE_AUTOMOC ON)
-set(CMAKE_AUTORCC ON)
-set(CMAKE_AUTOUIC ON)
-
-set(INSTALL_EXAMPLEDIR "examples")
-
-find_package(Qt6 COMPONENTS Xml)
-find_package(Qt6 COMPONENTS Widgets)
-
-add_qt_gui_executable(saxbookmarks
- main.cpp
- mainwindow.cpp mainwindow.h
- xbelgenerator.cpp xbelgenerator.h
- xbelhandler.cpp xbelhandler.h
-)
-target_link_libraries(saxbookmarks PUBLIC
- Qt::Widgets
- Qt::Xml
-)
-install(TARGETS saxbookmarks
- RUNTIME DESTINATION "${INSTALL_EXAMPLEDIR}"
- BUNDLE DESTINATION "${INSTALL_EXAMPLEDIR}"
- LIBRARY DESTINATION "${INSTALL_EXAMPLEDIR}"
-)
diff --git a/examples/xml/saxbookmarks/doc/images/saxbookmarks-example.png b/examples/xml/saxbookmarks/doc/images/saxbookmarks-example.png
deleted file mode 100644
index 54d793be56..0000000000
--- a/examples/xml/saxbookmarks/doc/images/saxbookmarks-example.png
+++ /dev/null
Binary files differ
diff --git a/examples/xml/saxbookmarks/jennifer.xbel b/examples/xml/saxbookmarks/jennifer.xbel
deleted file mode 100644
index 2501c118af..0000000000
--- a/examples/xml/saxbookmarks/jennifer.xbel
+++ /dev/null
@@ -1,69 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE xbel>
-<xbel version="1.0">
- <folder folded="no">
- <title>Qt Resources</title>
- <bookmark href="http://qt.io/">
- <title>Qt home page</title>
- </bookmark>
- <bookmark href="https://www.qt.io/partners/">
- <title>Qt Partners</title>
- </bookmark>
- <bookmark href="https://www.qt.io/qt-training/">
- <title>Training</title>
- </bookmark>
- <bookmark href="http://doc.qt.io/">
- <title>Qt 5 documentation</title>
- </bookmark>
- <bookmark href="http://qt-project.org/faq/">
- <title>Frequently Asked Questions</title>
- </bookmark>
- <folder folded="yes">
- <title>Community Resources</title>
- <bookmark href="http://www.qtcentre.org/content/">
- <title>Qt Centre</title>
- </bookmark>
- <bookmark href="http://www.qtforum.org/">
- <title>QtForum.org</title>
- </bookmark>
- <bookmark href="http://digitalfanatics.org/projects/qt_tutorial/">
- <title>The Independent Qt Tutorial</title>
- </bookmark>
- <bookmark href="http://www.qtforum.de/">
- <title>German Qt Forum</title>
- </bookmark>
- <bookmark href="http://www.korone.net/">
- <title>Korean Qt Community Site</title>
- </bookmark>
- <bookmark href="http://prog.org.ru/">
- <title>Russian Qt Forum</title>
- </bookmark>
- </folder>
- </folder>
- <folder folded="no">
- <title>Online Dictionaries</title>
- <bookmark href="http://www.dictionary.com/">
- <title>Dictionary.com</title>
- </bookmark>
- <bookmark href="http://www.m-w.com/">
- <title>Merriam-Webster Online</title>
- </bookmark>
- <bookmark href="http://dictionary.cambridge.org/">
- <title>Cambridge Dictionaries Online</title>
- </bookmark>
- <bookmark href="http://www.onelook.com/">
- <title>OneLook Dictionary Search</title>
- </bookmark>
- <separator/>
- <bookmark href="http://dict.tu-chemnitz.de/">
- <title>TU Chemnitz German-English Dictionary</title>
- </bookmark>
- <separator/>
- <bookmark href="http://atilf.atilf.fr/tlf.htm">
- <title>Trésor de la Langue Française informatisé</title>
- </bookmark>
- <bookmark href="http://dictionnaires.atilf.fr/dictionnaires/ACADEMIE/">
- <title>Dictionnaire de l'Académie Française</title>
- </bookmark>
- </folder>
-</xbel>
diff --git a/examples/xml/saxbookmarks/mainwindow.cpp b/examples/xml/saxbookmarks/mainwindow.cpp
deleted file mode 100644
index 8b7733081f..0000000000
--- a/examples/xml/saxbookmarks/mainwindow.cpp
+++ /dev/null
@@ -1,177 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the examples of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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"
-#include "xbelgenerator.h"
-#include "xbelhandler.h"
-
-MainWindow::MainWindow()
-{
- QStringList labels;
- labels << tr("Title") << tr("Location");
-
- treeWidget = new QTreeWidget;
- treeWidget->header()->setSectionResizeMode(QHeaderView::Stretch);
- treeWidget->setHeaderLabels(labels);
-#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_CLIPBOARD)
- treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(treeWidget, &QWidget::customContextMenuRequested,
- this, &MainWindow::onCustomContextMenuRequested);
-#endif
- setCentralWidget(treeWidget);
-
- createMenus();
-
- statusBar()->showMessage(tr("Ready"));
-
- setWindowTitle(tr("SAX Bookmarks"));
- const QSize availableSize = screen()->availableGeometry().size();
- resize(availableSize.width() / 2, availableSize.height() / 3);
-}
-
-#if !defined(QT_NO_CONTEXTMENU) && !defined(QT_NO_CLIPBOARD)
-void MainWindow::onCustomContextMenuRequested(const QPoint &pos)
-{
- const QTreeWidgetItem *item = treeWidget->itemAt(pos);
- if (!item)
- return;
- const QString url = item->text(1);
- QMenu contextMenu;
- QAction *copyAction = contextMenu.addAction(tr("Copy Link to Clipboard"));
- QAction *openAction = contextMenu.addAction(tr("Open"));
- QAction *action = contextMenu.exec(treeWidget->viewport()->mapToGlobal(pos));
- if (action == copyAction)
- QGuiApplication::clipboard()->setText(url);
- else if (action == openAction)
- QDesktopServices::openUrl(QUrl(url));
-}
-#endif // !QT_NO_CONTEXTMENU && !QT_NO_CLIPBOARD
-
-void MainWindow::open()
-{
- QString fileName =
- QFileDialog::getOpenFileName(this, tr("Open Bookmark File"),
- QDir::currentPath(),
- tr("XBEL Files (*.xbel *.xml)"));
- if (fileName.isEmpty())
- return;
-
- treeWidget->clear();
-
- XbelHandler handler(treeWidget);
- QXmlSimpleReader reader;
- reader.setContentHandler(&handler);
- reader.setErrorHandler(&handler);
-
- QFile file(fileName);
- if (!file.open(QFile::ReadOnly | QFile::Text)) {
- QMessageBox::warning(this, tr("SAX Bookmarks"),
- tr("Cannot read file %1:\n%2.")
- .arg(QDir::toNativeSeparators(fileName),
- file.errorString()));
- return;
- }
-
- QXmlInputSource xmlInputSource(&file);
- if (reader.parse(xmlInputSource))
- statusBar()->showMessage(tr("File loaded"), 2000);
-}
-
-void MainWindow::saveAs()
-{
- QString fileName =
- QFileDialog::getSaveFileName(this, tr("Save Bookmark File"),
- QDir::currentPath(),
- tr("XBEL Files (*.xbel *.xml)"));
- if (fileName.isEmpty())
- return;
-
- QFile file(fileName);
- if (!file.open(QFile::WriteOnly | QFile::Text)) {
- QMessageBox::warning(this, tr("SAX Bookmarks"),
- tr("Cannot write file %1:\n%2.")
- .arg(QDir::toNativeSeparators(fileName),
- file.errorString()));
- return;
- }
-
- XbelGenerator generator(treeWidget);
- if (generator.write(&file))
- statusBar()->showMessage(tr("File saved"), 2000);
-}
-
-void MainWindow::about()
-{
- QMessageBox::about(this, tr("About SAX Bookmarks"),
- tr("The <b>SAX Bookmarks</b> example demonstrates how to use Qt's "
- "SAX classes to read XML documents and how to generate XML by "
- "hand."));
-}
-
-void MainWindow::createMenus()
-{
- QMenu *fileMenu = menuBar()->addMenu(tr("&File"));
- QAction *openAct = fileMenu->addAction(tr("&Open..."), this, &MainWindow::open);
- openAct->setShortcuts(QKeySequence::Open);
-
- QAction *saveAsAct = fileMenu->addAction(tr("&Save As..."), this, &MainWindow::saveAs);
- saveAsAct->setShortcuts(QKeySequence::SaveAs);
-
- QAction *exitAct = fileMenu->addAction(tr("E&xit"), this, &QWidget::close);
- exitAct->setShortcuts(QKeySequence::Quit);
-
- menuBar()->addSeparator();
-
- QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
- helpMenu->addAction(tr("&About"), this, &MainWindow::about);
- helpMenu->addAction(tr("About &Qt"), qApp, &QCoreApplication::quit);
-}
diff --git a/examples/xml/saxbookmarks/saxbookmarks.pro b/examples/xml/saxbookmarks/saxbookmarks.pro
deleted file mode 100644
index af2a124a13..0000000000
--- a/examples/xml/saxbookmarks/saxbookmarks.pro
+++ /dev/null
@@ -1,15 +0,0 @@
-HEADERS = mainwindow.h \
- xbelgenerator.h \
- xbelhandler.h
-SOURCES = main.cpp \
- mainwindow.cpp \
- xbelgenerator.cpp \
- xbelhandler.cpp
-QT += xml widgets
-requires(qtConfig(filedialog))
-
-EXAMPLE_FILES = frank.xbel jennifer.xbel
-
-# install
-target.path = $$[QT_INSTALL_EXAMPLES]/xml/saxbookmarks
-INSTALLS += target
diff --git a/examples/xml/saxbookmarks/xbelgenerator.cpp b/examples/xml/saxbookmarks/xbelgenerator.cpp
deleted file mode 100644
index 77cb6748fe..0000000000
--- a/examples/xml/saxbookmarks/xbelgenerator.cpp
+++ /dev/null
@@ -1,124 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the examples of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 "xbelgenerator.h"
-
-XbelGenerator::XbelGenerator(const QTreeWidget *treeWidget)
- : treeWidget(treeWidget)
-{
-}
-
-bool XbelGenerator::write(QIODevice *device)
-{
- out.setDevice(device);
- out.setCodec("UTF-8");
- out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- << "<!DOCTYPE xbel>\n"
- << "<xbel version=\"1.0\">\n";
-
- for (int i = 0; i < treeWidget->topLevelItemCount(); ++i)
- generateItem(treeWidget->topLevelItem(i), 1);
-
- out << "</xbel>\n";
- return true;
-}
-
-QString XbelGenerator::indent(int depth)
-{
- const int IndentSize = 4;
- return QString(IndentSize * depth, ' ');
-}
-
-QString XbelGenerator::escapedText(const QString &str)
-{
- QString result = str;
- result.replace('&', "&amp;");
- result.replace('<', "&lt;");
- result.replace('>', "&gt;");
- return result;
-}
-
-QString XbelGenerator::escapedAttribute(const QString &str)
-{
- QString result = escapedText(str);
- result.replace(QLatin1Char('"'), "&quot;");
- result.prepend(QLatin1Char('"'));
- result.append(QLatin1Char('"'));
- return result;
-}
-
-void XbelGenerator::generateItem(const QTreeWidgetItem *item, int depth)
-{
- QString tagName = item->data(0, Qt::UserRole).toString();
- if (tagName == QLatin1String("folder")) {
- bool folded = !item->isExpanded();
- out << indent(depth) << "<folder folded=\"" << (folded ? "yes" : "no")
- << "\">\n"
- << indent(depth + 1) << "<title>" << escapedText(item->text(0))
- << "</title>\n";
-
- for (int i = 0; i < item->childCount(); ++i)
- generateItem(item->child(i), depth + 1);
-
- out << indent(depth) << "</folder>\n";
- } else if (tagName == QLatin1String("bookmark")) {
- out << indent(depth) << "<bookmark";
- if (!item->text(1).isEmpty())
- out << " href=" << escapedAttribute(item->text(1));
- out << ">\n"
- << indent(depth + 1) << "<title>" << escapedText(item->text(0))
- << "</title>\n"
- << indent(depth) << "</bookmark>\n";
- } else if (tagName == QLatin1String("separator")) {
- out << indent(depth) << "<separator/>\n";
- }
-}
diff --git a/examples/xml/saxbookmarks/xbelgenerator.h b/examples/xml/saxbookmarks/xbelgenerator.h
deleted file mode 100644
index abfabfd75c..0000000000
--- a/examples/xml/saxbookmarks/xbelgenerator.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the examples of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 XBELGENERATOR_H
-#define XBELGENERATOR_H
-
-#include <QTextStream>
-
-QT_BEGIN_NAMESPACE
-class QTreeWidget;
-class QTreeWidgetItem;
-QT_END_NAMESPACE
-
-class XbelGenerator
-{
-public:
- explicit XbelGenerator(const QTreeWidget *treeWidget);
-
- bool write(QIODevice *device);
-
-private:
- static QString indent(int indentLevel);
- static QString escapedText(const QString &str);
- static QString escapedAttribute(const QString &str);
- void generateItem(const QTreeWidgetItem *item, int depth);
-
- const QTreeWidget *treeWidget;
- QTextStream out;
-};
-
-#endif
diff --git a/examples/xml/saxbookmarks/xbelhandler.cpp b/examples/xml/saxbookmarks/xbelhandler.cpp
deleted file mode 100644
index 62dfbf9482..0000000000
--- a/examples/xml/saxbookmarks/xbelhandler.cpp
+++ /dev/null
@@ -1,160 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the examples of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 "xbelhandler.h"
-
-static inline QString versionAttribute() { return QStringLiteral("version"); }
-static inline QString hrefAttribute() { return QStringLiteral("href"); }
-static inline QString foldedAttribute() { return QStringLiteral("folded"); }
-
-XbelHandler::XbelHandler(QTreeWidget *treeWidget)
- : treeWidget(treeWidget)
-{
- item = 0;
- metXbelTag = false;
-
- QStyle *style = treeWidget->style();
-
- folderIcon.addPixmap(style->standardPixmap(QStyle::SP_DirClosedIcon),
- QIcon::Normal, QIcon::Off);
- folderIcon.addPixmap(style->standardPixmap(QStyle::SP_DirOpenIcon),
- QIcon::Normal, QIcon::On);
- bookmarkIcon.addPixmap(style->standardPixmap(QStyle::SP_FileIcon));
-}
-
-bool XbelHandler::startElement(const QString & /* namespaceURI */,
- const QString & /* localName */,
- const QString &qName,
- const QXmlAttributes &attributes)
-{
- if (!metXbelTag && qName != QLatin1String("xbel")) {
- errorStr = QObject::tr("The file is not an XBEL file.");
- return false;
- }
-
- if (qName == QLatin1String("xbel")) {
- QString version = attributes.value(versionAttribute());
- if (!version.isEmpty() && version != QLatin1String("1.0")) {
- errorStr = QObject::tr("The file is not an XBEL version 1.0 file.");
- return false;
- }
- metXbelTag = true;
- } else if (qName == QLatin1String("folder")) {
- item = createChildItem(qName);
- item->setFlags(item->flags() | Qt::ItemIsEditable);
- item->setIcon(0, folderIcon);
- item->setText(0, QObject::tr("Folder"));
- bool folded = (attributes.value(foldedAttribute()) != QLatin1String("no"));
- item->setExpanded(!folded);
- } else if (qName == QLatin1String("bookmark")) {
- item = createChildItem(qName);
- item->setFlags(item->flags() | Qt::ItemIsEditable);
- item->setIcon(0, bookmarkIcon);
- item->setText(0, QObject::tr("Unknown title"));
- item->setText(1, attributes.value(hrefAttribute()));
- } else if (qName == QLatin1String("separator")) {
- item = createChildItem(qName);
- item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
- item->setText(0, QString(30, 0xB7));
- }
-
- currentText.clear();
- return true;
-}
-
-bool XbelHandler::endElement(const QString & /* namespaceURI */,
- const QString & /* localName */,
- const QString &qName)
-{
- if (qName == QLatin1String("title")) {
- if (item)
- item->setText(0, currentText);
- } else if (qName == QLatin1String("folder") || qName == QLatin1String("bookmark")
- || qName == QLatin1String("separator")) {
- item = item->parent();
- }
- return true;
-}
-
-bool XbelHandler::characters(const QString &str)
-{
- currentText += str;
- return true;
-}
-
-bool XbelHandler::fatalError(const QXmlParseException &exception)
-{
- QMessageBox::information(treeWidget->window(), QObject::tr("SAX Bookmarks"),
- QObject::tr("Parse error at line %1, column %2:\n"
- "%3")
- .arg(exception.lineNumber())
- .arg(exception.columnNumber())
- .arg(exception.message()));
- return false;
-}
-
-QString XbelHandler::errorString() const
-{
- return errorStr;
-}
-
-QTreeWidgetItem *XbelHandler::createChildItem(const QString &tagName)
-{
- QTreeWidgetItem *childItem;
- if (item) {
- childItem = new QTreeWidgetItem(item);
- } else {
- childItem = new QTreeWidgetItem(treeWidget);
- }
- childItem->setData(0, Qt::UserRole, tagName);
- return childItem;
-}
diff --git a/examples/xml/saxbookmarks/xbelhandler.h b/examples/xml/saxbookmarks/xbelhandler.h
deleted file mode 100644
index 3f4cb109e9..0000000000
--- a/examples/xml/saxbookmarks/xbelhandler.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the examples of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:BSD$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** BSD License Usage
-** Alternatively, 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 The Qt Company Ltd 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 XBELHANDLER_H
-#define XBELHANDLER_H
-
-#include <QIcon>
-#include <QXmlDefaultHandler>
-
-QT_BEGIN_NAMESPACE
-class QTreeWidget;
-class QTreeWidgetItem;
-QT_END_NAMESPACE
-
-class XbelHandler : public QXmlDefaultHandler
-{
-public:
- XbelHandler(QTreeWidget *treeWidget);
-
- bool startElement(const QString &namespaceURI, const QString &localName,
- const QString &qName, const QXmlAttributes &attributes) override;
- bool endElement(const QString &namespaceURI, const QString &localName,
- const QString &qName) override;
- bool characters(const QString &str) override;
- bool fatalError(const QXmlParseException &exception) override;
- QString errorString() const override;
-
-private:
- QTreeWidgetItem *createChildItem(const QString &tagName);
-
- QTreeWidget *treeWidget;
- QTreeWidgetItem *item;
- QString currentText;
- QString errorStr;
- bool metXbelTag;
-
- QIcon folderIcon;
- QIcon bookmarkIcon;
-};
-
-#endif
diff --git a/examples/xml/xml.pro b/examples/xml/xml.pro
index 72bf95b2ea..b0750574f4 100644
--- a/examples/xml/xml.pro
+++ b/examples/xml/xml.pro
@@ -4,7 +4,6 @@ SUBDIRS = htmlinfo \
qtHaveModule(widgets) {
SUBDIRS += dombookmarks \
- saxbookmarks \
streambookmarks
qtHaveModule(network): SUBDIRS += \