summaryrefslogtreecommitdiffstats
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/corelib/serialization/convert/cborconverter.cpp2
-rw-r--r--examples/corelib/serialization/convert/textconverter.cpp6
-rw-r--r--examples/corelib/tools/doc/src/customtype.qdoc7
-rw-r--r--examples/embedded/raycasting/raycasting.cpp4
-rw-r--r--examples/network/bearermonitor/bearermonitor.pro2
-rw-r--r--examples/network/downloadmanager/downloadmanager.cpp4
-rw-r--r--examples/network/downloadmanager/downloadmanager.h2
-rw-r--r--examples/network/http/httpwindow.cpp24
-rw-r--r--examples/network/http/httpwindow.h8
-rw-r--r--examples/network/secureudpserver/server.cpp23
-rw-r--r--examples/network/secureudpserver/server.h8
-rw-r--r--examples/network/torrent/ratecontroller.cpp14
-rw-r--r--examples/network/torrent/ratecontroller.h4
-rw-r--r--examples/network/torrent/torrentclient.cpp60
-rw-r--r--examples/opengl/contextinfo/widget.cpp2
-rw-r--r--examples/opengl/legacy/overpainting/glwidget.cpp6
-rw-r--r--examples/opengl/qopenglwidget/glwidget.cpp7
-rw-r--r--examples/opengl/qopenglwidget/glwidget.h4
-rw-r--r--examples/opengl/threadedqopenglwidget/main.cpp6
-rw-r--r--examples/qtconcurrent/wordcount/main.cpp19
-rw-r--r--examples/sql/relationaltablemodel/relationaltablemodel.cpp10
-rw-r--r--examples/vulkan/hellovulkancubes/renderer.cpp7
-rw-r--r--examples/vulkan/hellovulkanwidget/hellovulkanwidget.cpp14
-rw-r--r--examples/widgets/dialogs/standarddialogs/dialog.cpp1
-rw-r--r--examples/widgets/doc/src/application.qdoc9
-rw-r--r--examples/widgets/doc/src/icons.qdoc7
-rw-r--r--examples/widgets/graphicsview/boxes/scene.cpp2
-rw-r--r--examples/widgets/graphicsview/boxes/scene.h2
-rw-r--r--examples/widgets/graphicsview/diagramscene/arrow.cpp12
-rw-r--r--examples/widgets/graphicsview/diagramscene/mainwindow.cpp4
-rw-r--r--examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp2
-rw-r--r--examples/widgets/mainwindows/application/mainwindow.cpp32
-rw-r--r--examples/widgets/mainwindows/mdi/mdichild.cpp27
-rw-r--r--examples/widgets/mainwindows/sdi/mainwindow.cpp27
-rw-r--r--examples/widgets/painting/affine/xform.cpp5
-rw-r--r--examples/widgets/painting/composition/composition.cpp12
-rw-r--r--examples/widgets/painting/composition/composition.h10
-rw-r--r--examples/widgets/painting/composition/main.cpp6
-rw-r--r--examples/widgets/painting/deform/pathdeform.h4
-rw-r--r--examples/widgets/painting/gradients/gradients.cpp6
-rw-r--r--examples/widgets/painting/pathstroke/pathstroke.cpp3
-rw-r--r--examples/widgets/painting/shared/hoverpoints.cpp3
-rw-r--r--examples/widgets/qnx/foreignwindows/collector.cpp176
-rw-r--r--examples/widgets/qnx/foreignwindows/collector.h75
-rw-r--r--examples/widgets/qnx/foreignwindows/foreignwindows.pro11
-rw-r--r--examples/widgets/qnx/foreignwindows/main.cpp53
-rw-r--r--examples/widgets/richtext/textedit/example.md102
-rw-r--r--examples/widgets/richtext/textedit/images/mac/checkbox-checked.pngbin0 -> 1167 bytes
-rw-r--r--examples/widgets/richtext/textedit/images/mac/checkbox.pngbin0 -> 779 bytes
-rw-r--r--examples/widgets/richtext/textedit/images/mac/format-indent-less.pngbin0 -> 1201 bytes
-rw-r--r--examples/widgets/richtext/textedit/images/mac/format-indent-more.pngbin0 -> 993 bytes
-rw-r--r--examples/widgets/richtext/textedit/images/win/checkbox-checked.pngbin0 -> 1167 bytes
-rw-r--r--examples/widgets/richtext/textedit/images/win/checkbox.pngbin0 -> 779 bytes
-rw-r--r--examples/widgets/richtext/textedit/images/win/format-indent-less.pngbin0 -> 1201 bytes
-rw-r--r--examples/widgets/richtext/textedit/images/win/format-indent-more.pngbin0 -> 993 bytes
-rw-r--r--examples/widgets/richtext/textedit/textedit.cpp151
-rw-r--r--examples/widgets/richtext/textedit/textedit.h7
-rw-r--r--examples/widgets/richtext/textedit/textedit.qrc8
-rw-r--r--examples/widgets/statemachine/factorial/main.cpp3
-rw-r--r--examples/widgets/tools/i18n/languagechooser.cpp7
-rw-r--r--examples/widgets/tools/plugandpaint/app/interfaces.h6
-rw-r--r--examples/widgets/tools/plugandpaint/app/paintarea.cpp2
-rw-r--r--examples/widgets/widgets/charactermap/mainwindow.cpp4
-rw-r--r--examples/widgets/widgets/icons/iconpreviewarea.cpp40
-rw-r--r--examples/widgets/widgets/icons/mainwindow.cpp6
-rw-r--r--examples/widgets/widgets/imageviewer/imageviewer.cpp2
-rw-r--r--examples/widgets/widgets/spinboxes/window.cpp2
-rw-r--r--examples/widgets/widgets/styles/widgetgallery.cpp2
-rw-r--r--examples/xml/htmlinfo/main.cpp18
69 files changed, 811 insertions, 281 deletions
diff --git a/examples/corelib/serialization/convert/cborconverter.cpp b/examples/corelib/serialization/convert/cborconverter.cpp
index ad69983eb1..f907bb0af6 100644
--- a/examples/corelib/serialization/convert/cborconverter.cpp
+++ b/examples/corelib/serialization/convert/cborconverter.cpp
@@ -226,7 +226,7 @@ void CborDiagnosticDumper::saveFile(QIODevice *f, const QVariant &contents, cons
QTextStream out(f);
out << convertFromVariant(contents, Double).toDiagnosticNotation(opts)
- << endl;
+ << Qt::endl;
}
CborConverter::CborConverter()
diff --git a/examples/corelib/serialization/convert/textconverter.cpp b/examples/corelib/serialization/convert/textconverter.cpp
index e80e69a0b5..7aed08f96c 100644
--- a/examples/corelib/serialization/convert/textconverter.cpp
+++ b/examples/corelib/serialization/convert/textconverter.cpp
@@ -66,7 +66,7 @@ static void dumpVariant(QTextStream &out, const QVariant &v)
case QVariant::String: {
const QStringList list = v.toStringList();
for (const QString &s : list)
- out << s << endl;
+ out << s << Qt::endl;
break;
}
@@ -80,11 +80,11 @@ static void dumpVariant(QTextStream &out, const QVariant &v)
}
case QMetaType::Nullptr:
- out << "(null)" << endl;
+ out << "(null)" << Qt::endl;
break;
default:
- out << v.toString() << endl;
+ out << v.toString() << Qt::endl;
break;
}
}
diff --git a/examples/corelib/tools/doc/src/customtype.qdoc b/examples/corelib/tools/doc/src/customtype.qdoc
index 91b814808a..7ccfc95c70 100644
--- a/examples/corelib/tools/doc/src/customtype.qdoc
+++ b/examples/corelib/tools/doc/src/customtype.qdoc
@@ -117,8 +117,8 @@
\snippet tools/customtype/main.cpp storing a custom value
- Alternatively, the QVariant::fromValue() and qVariantSetValue() functions
- can be used if you are using a compiler without support for member template
+ Alternatively, the QVariant::fromValue() function can be used if
+ you are using a compiler without support for member template
functions.
The value can be retrieved using the QVariant::value() member template
@@ -126,9 +126,6 @@
\snippet tools/customtype/main.cpp retrieving a custom value
- Alternatively, the qVariantValue() template function can be used if
- you are using a compiler without support for member template functions.
-
\section1 Further Reading
The custom \c Message type can also be used with direct signal-slot
diff --git a/examples/embedded/raycasting/raycasting.cpp b/examples/embedded/raycasting/raycasting.cpp
index d37b9f5d2e..7213811213 100644
--- a/examples/embedded/raycasting/raycasting.cpp
+++ b/examples/embedded/raycasting/raycasting.cpp
@@ -255,11 +255,7 @@ public:
protected:
void resizeEvent(QResizeEvent*) {
-#if defined(Q_OS_WINCE_WM)
- touchDevice = true;
-#else
touchDevice = false;
-#endif
if (touchDevice) {
if (width() < height()) {
trackPad = QRect(0, height() / 2, width(), height() / 2);
diff --git a/examples/network/bearermonitor/bearermonitor.pro b/examples/network/bearermonitor/bearermonitor.pro
index 7d90b408e0..16ac41298a 100644
--- a/examples/network/bearermonitor/bearermonitor.pro
+++ b/examples/network/bearermonitor/bearermonitor.pro
@@ -13,7 +13,7 @@ FORMS = bearermonitor_240_320.ui \
bearermonitor_640_480.ui \
sessionwidget.ui
-win32:LIBS += -lws2_32
+win32: QMAKE_USE += ws2_32
CONFIG += console
diff --git a/examples/network/downloadmanager/downloadmanager.cpp b/examples/network/downloadmanager/downloadmanager.cpp
index e820b4ff70..9e0c03c6af 100644
--- a/examples/network/downloadmanager/downloadmanager.cpp
+++ b/examples/network/downloadmanager/downloadmanager.cpp
@@ -132,7 +132,7 @@ void DownloadManager::startNextDownload()
// prepare the output
printf("Downloading %s...\n", url.toEncoded().constData());
- downloadTime.start();
+ downloadTimer.start();
}
void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
@@ -140,7 +140,7 @@ void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
progressBar.setStatus(bytesReceived, bytesTotal);
// calculate the download speed
- double speed = bytesReceived * 1000.0 / downloadTime.elapsed();
+ double speed = bytesReceived * 1000.0 / downloadTimer.elapsed();
QString unit;
if (speed < 1024) {
unit = "bytes/sec";
diff --git a/examples/network/downloadmanager/downloadmanager.h b/examples/network/downloadmanager/downloadmanager.h
index 4bc6351ff9..818a774f1f 100644
--- a/examples/network/downloadmanager/downloadmanager.h
+++ b/examples/network/downloadmanager/downloadmanager.h
@@ -83,7 +83,7 @@ private:
QQueue<QUrl> downloadQueue;
QNetworkReply *currentDownload = nullptr;
QFile output;
- QTime downloadTime;
+ QElapsedTimer downloadTimer;
TextProgressBar progressBar;
int downloadedCount = 0;
diff --git a/examples/network/http/httpwindow.cpp b/examples/network/http/httpwindow.cpp
index 39ffb3cc87..c7bf0c0dff 100644
--- a/examples/network/http/httpwindow.cpp
+++ b/examples/network/http/httpwindow.cpp
@@ -48,13 +48,14 @@
**
****************************************************************************/
+#include "httpwindow.h"
+
+#include "ui_authenticationdialog.h"
+
#include <QtWidgets>
#include <QtNetwork>
#include <QUrl>
-#include "httpwindow.h"
-#include "ui_authenticationdialog.h"
-
#if QT_CONFIG(ssl)
const char defaultUrl[] = "https://www.qt.io/";
#else
@@ -74,6 +75,10 @@ ProgressDialog::ProgressDialog(const QUrl &url, QWidget *parent)
setMinimumSize(QSize(400, 75));
}
+ProgressDialog::~ProgressDialog()
+{
+}
+
void ProgressDialog::networkReplyProgress(qint64 bytesRead, qint64 totalBytes)
{
setMaximum(totalBytes);
@@ -137,6 +142,10 @@ HttpWindow::HttpWindow(QWidget *parent)
urlLineEdit->setFocus();
}
+HttpWindow::~HttpWindow()
+{
+}
+
void HttpWindow::startRequest(const QUrl &requestedUrl)
{
url = requestedUrl;
@@ -204,9 +213,9 @@ void HttpWindow::downloadFile()
startRequest(newUrl);
}
-QFile *HttpWindow::openFileForWrite(const QString &fileName)
+std::unique_ptr<QFile> HttpWindow::openFileForWrite(const QString &fileName)
{
- QScopedPointer<QFile> file(new QFile(fileName));
+ std::unique_ptr<QFile> file(new QFile(fileName));
if (!file->open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("Error"),
tr("Unable to save the file %1: %2.")
@@ -214,7 +223,7 @@ QFile *HttpWindow::openFileForWrite(const QString &fileName)
file->errorString()));
return nullptr;
}
- return file.take();
+ return file;
}
void HttpWindow::cancelDownload()
@@ -231,8 +240,7 @@ void HttpWindow::httpFinished()
if (file) {
fi.setFile(file->fileName());
file->close();
- delete file;
- file = nullptr;
+ file.reset();
}
if (httpRequestAborted) {
diff --git a/examples/network/http/httpwindow.h b/examples/network/http/httpwindow.h
index 20ad2bb4da..f7bd0047de 100644
--- a/examples/network/http/httpwindow.h
+++ b/examples/network/http/httpwindow.h
@@ -55,6 +55,8 @@
#include <QNetworkAccessManager>
#include <QUrl>
+#include <memory>
+
QT_BEGIN_NAMESPACE
class QFile;
class QLabel;
@@ -72,6 +74,7 @@ class ProgressDialog : public QProgressDialog {
public:
explicit ProgressDialog(const QUrl &url, QWidget *parent = nullptr);
+ ~ProgressDialog();
public slots:
void networkReplyProgress(qint64 bytesRead, qint64 totalBytes);
@@ -83,6 +86,7 @@ class HttpWindow : public QDialog
public:
explicit HttpWindow(QWidget *parent = nullptr);
+ ~HttpWindow();
void startRequest(const QUrl &requestedUrl);
@@ -98,7 +102,7 @@ private slots:
#endif
private:
- QFile *openFileForWrite(const QString &fileName);
+ std::unique_ptr<QFile> openFileForWrite(const QString &fileName);
QLabel *statusLabel;
QLineEdit *urlLineEdit;
@@ -110,7 +114,7 @@ private:
QUrl url;
QNetworkAccessManager qnam;
QNetworkReply *reply;
- QFile *file;
+ std::unique_ptr<QFile> file;
bool httpRequestAborted;
};
diff --git a/examples/network/secureudpserver/server.cpp b/examples/network/secureudpserver/server.cpp
index 0d83fa9b51..450eb9e68d 100644
--- a/examples/network/secureudpserver/server.cpp
+++ b/examples/network/secureudpserver/server.cpp
@@ -62,7 +62,7 @@ QString peer_info(const QHostAddress &address, quint16 port)
return info.arg(address.toString()).arg(port);
}
-QString connection_info(QSharedPointer<QDtls> connection)
+QString connection_info(QDtls *connection)
{
QString info(DtlsServer::tr("Session cipher: "));
info += connection->sessionCipher().name();
@@ -157,7 +157,7 @@ void DtlsServer::readyRead()
}
const auto client = std::find_if(knownClients.begin(), knownClients.end(),
- [&](const DtlsConnection &connection){
+ [&](const std::unique_ptr<QDtls> &connection){
return connection->peerAddress() == peerAddress
&& connection->peerPort() == peerPort;
});
@@ -170,7 +170,7 @@ void DtlsServer::readyRead()
//! [6]
if ((*client)->isConnectionEncrypted()) {
- decryptDatagram(*client, dgram);
+ decryptDatagram(client->get(), dgram);
if ((*client)->dtlsError() == QDtlsError::RemoteClosedConnectionError)
knownClients.erase(client);
return;
@@ -178,7 +178,7 @@ void DtlsServer::readyRead()
//! [6]
//! [7]
- doHandshake(*client, dgram);
+ doHandshake(client->get(), dgram);
//! [7]
}
@@ -205,13 +205,13 @@ void DtlsServer::handleNewConnection(const QHostAddress &peerAddress,
emit infoMessage(peerInfo + tr(": verified, starting a handshake"));
//! [8]
//! [9]
- DtlsConnection newConnection(new QDtls(QSslSocket::SslServerMode));
+ std::unique_ptr<QDtls> newConnection{new QDtls{QSslSocket::SslServerMode}};
newConnection->setDtlsConfiguration(serverConfiguration);
newConnection->setPeer(peerAddress, peerPort);
- newConnection->connect(newConnection.data(), &QDtls::pskRequired,
+ newConnection->connect(newConnection.get(), &QDtls::pskRequired,
this, &DtlsServer::pskRequired);
- knownClients.push_back(newConnection);
- doHandshake(newConnection, clientHello);
+ knownClients.push_back(std::move(newConnection));
+ doHandshake(knownClients.back().get(), clientHello);
//! [9]
} else if (cookieSender.dtlsError() != QDtlsError::NoError) {
emit errorMessage(tr("DTLS error: ") + cookieSender.dtlsErrorString());
@@ -221,7 +221,7 @@ void DtlsServer::handleNewConnection(const QHostAddress &peerAddress,
}
//! [11]
-void DtlsServer::doHandshake(DtlsConnection newConnection, const QByteArray &clientHello)
+void DtlsServer::doHandshake(QDtls *newConnection, const QByteArray &clientHello)
{
const bool result = newConnection->doHandshake(&serverSocket, clientHello);
if (!result) {
@@ -246,7 +246,7 @@ void DtlsServer::doHandshake(DtlsConnection newConnection, const QByteArray &cli
//! [11]
//! [12]
-void DtlsServer::decryptDatagram(DtlsConnection connection, const QByteArray &clientMessage)
+void DtlsServer::decryptDatagram(QDtls *connection, const QByteArray &clientMessage)
{
Q_ASSERT(connection->isConnectionEncrypted());
@@ -266,10 +266,9 @@ void DtlsServer::decryptDatagram(DtlsConnection connection, const QByteArray &cl
//! [14]
void DtlsServer::shutdown()
{
- for (DtlsConnection &connection : knownClients)
+ for (const auto &connection : qExchange(knownClients, {}))
connection->shutdown(&serverSocket);
- knownClients.clear();
serverSocket.close();
}
//! [14]
diff --git a/examples/network/secureudpserver/server.h b/examples/network/secureudpserver/server.h
index b720368e7b..1af8aef8a2 100644
--- a/examples/network/secureudpserver/server.h
+++ b/examples/network/secureudpserver/server.h
@@ -54,6 +54,7 @@
#include <QtNetwork>
#include <vector>
+#include <memory>
QT_BEGIN_NAMESPACE
@@ -86,9 +87,8 @@ private:
void handleNewConnection(const QHostAddress &peerAddress, quint16 peerPort,
const QByteArray &clientHello);
- using DtlsConnection = QSharedPointer<QDtls>;
- void doHandshake(DtlsConnection newConnection, const QByteArray &clientHello);
- void decryptDatagram(DtlsConnection connection, const QByteArray &clientMessage);
+ void doHandshake(QDtls *newConnection, const QByteArray &clientHello);
+ void decryptDatagram(QDtls *connection, const QByteArray &clientMessage);
void shutdown();
bool listening = false;
@@ -96,7 +96,7 @@ private:
QSslConfiguration serverConfiguration;
QDtlsClientVerifier cookieSender;
- QVector<DtlsConnection> knownClients;
+ std::vector<std::unique_ptr<QDtls>> knownClients;
Q_DISABLE_COPY(DtlsServer)
};
diff --git a/examples/network/torrent/ratecontroller.cpp b/examples/network/torrent/ratecontroller.cpp
index 47b49dba30..96474806f5 100644
--- a/examples/network/torrent/ratecontroller.cpp
+++ b/examples/network/torrent/ratecontroller.cpp
@@ -96,8 +96,8 @@ void RateController::transfer()
if (sockets.isEmpty())
return;
- int msecs = 1000;
- if (!stopWatch.isNull())
+ qint64 msecs = 1000;
+ if (stopWatch.isValid())
msecs = qMin(msecs, stopWatch.elapsed());
qint64 bytesToWrite = (upLimit * msecs) / 1000;
@@ -123,11 +123,11 @@ void RateController::transfer()
qint64 writeChunk = qMax<qint64>(1, bytesToWrite / pendingSockets.size());
qint64 readChunk = qMax<qint64>(1, bytesToRead / pendingSockets.size());
- QSetIterator<PeerWireClient *> it(pendingSockets);
- while (it.hasNext() && (bytesToWrite > 0 || bytesToRead > 0)) {
- PeerWireClient *socket = it.next();
+ for (auto it = pendingSockets.begin(), end = pendingSockets.end(); it != end && (bytesToWrite > 0 || bytesToRead > 0); /*erasing*/) {
+ auto current = it++;
+ PeerWireClient *socket = *current;
if (socket->state() != QAbstractSocket::ConnectedState) {
- pendingSockets.remove(socket);
+ pendingSockets.erase(current);
continue;
}
@@ -156,7 +156,7 @@ void RateController::transfer()
if (dataTransferred && socket->canTransferMore())
canTransferMore = true;
else
- pendingSockets.remove(socket);
+ pendingSockets.erase(current);
}
} while (canTransferMore && (bytesToWrite > 0 || bytesToRead > 0) && !pendingSockets.isEmpty());
diff --git a/examples/network/torrent/ratecontroller.h b/examples/network/torrent/ratecontroller.h
index a4aa596ce1..f8bff0cc36 100644
--- a/examples/network/torrent/ratecontroller.h
+++ b/examples/network/torrent/ratecontroller.h
@@ -53,7 +53,7 @@
#include <QObject>
#include <QSet>
-#include <QTime>
+#include <QElapsedTimer>
class PeerWireClient;
@@ -79,7 +79,7 @@ public slots:
void scheduleTransfer();
private:
- QTime stopWatch;
+ QElapsedTimer stopWatch;
QSet<PeerWireClient *> sockets;
int upLimit;
int downLimit;
diff --git a/examples/network/torrent/torrentclient.cpp b/examples/network/torrent/torrentclient.cpp
index d01a5f3d9e..bddf3caa1a 100644
--- a/examples/network/torrent/torrentclient.cpp
+++ b/examples/network/torrent/torrentclient.cpp
@@ -720,9 +720,9 @@ QList<TorrentPeer *> TorrentClient::weighedFreePeers() const
qint64 now = QDateTime::currentSecsSinceEpoch();
QList<TorrentPeer *> freePeers;
QMap<QString, int> connectionsPerPeer;
- for (TorrentPeer *peer : d->peers) {
+ for (TorrentPeer *peer : qAsConst(d->peers)) {
bool busy = false;
- for (PeerWireClient *client : d->connections) {
+ for (PeerWireClient *client : qAsConst(d->connections)) {
if (client->state() == PeerWireClient::ConnectedState
&& client->peerAddress() == peer->address
&& client->peerPort() == peer->port) {
@@ -874,8 +874,7 @@ void TorrentClient::removeClient()
// Remove the client from RateController and all structures.
RateController::instance()->removeSocket(client);
d->connections.removeAll(client);
- QMultiMap<PeerWireClient *, TorrentPiece *>::Iterator it = d->payloads.find(client);
- while (it != d->payloads.end() && it.key() == client) {
+ for (auto it = d->payloads.find(client); it != d->payloads.end() && it.key() == client; /*erasing*/) {
TorrentPiece *piece = it.value();
piece->inProgress = false;
piece->requestedBlocks.fill(false);
@@ -883,9 +882,12 @@ void TorrentClient::removeClient()
}
// Remove pending read requests.
- QMapIterator<int, PeerWireClient *> it2(d->readIds);
- while (it2.findNext(client))
- d->readIds.remove(it2.key());
+ for (auto it = d->readIds.begin(), end = d->readIds.end(); it != end; /*erasing*/) {
+ if (it.value() == client)
+ it = d->readIds.erase(it);
+ else
+ ++it;
+ }
// Delete the client later.
disconnect(client, SIGNAL(disconnected()), this, SLOT(removeClient()));
@@ -1084,25 +1086,25 @@ void TorrentClient::scheduleUploads()
// seeding, we sort by upload speed. Seeds are left out; there's
// no use in unchoking them.
QList<PeerWireClient *> allClients = d->connections;
- QMultiMap<int, PeerWireClient *> transferSpeeds;
+ QVector<QPair<qint64, PeerWireClient *>> transferSpeeds;
for (PeerWireClient *client : qAsConst(allClients)) {
if (client->state() == QAbstractSocket::ConnectedState
&& client->availablePieces().count(true) != d->pieceCount) {
if (d->state == Seeding) {
- transferSpeeds.insert(client->uploadSpeed(), client);
+ transferSpeeds.push_back({client->uploadSpeed(), client});
} else {
- transferSpeeds.insert(client->downloadSpeed(), client);
+ transferSpeeds.push_back({client->downloadSpeed(), client});
}
}
}
+ std::sort(transferSpeeds.begin(), transferSpeeds.end());
+
// Unchoke the top 'MaxUploads' downloaders (peers that we are
// uploading to) and choke all others.
int maxUploaders = MaxUploads;
- QMapIterator<int, PeerWireClient *> it(transferSpeeds);
- it.toBack();
- while (it.hasPrevious()) {
- PeerWireClient *client = it.previous().value();
+ for (auto rit = transferSpeeds.crbegin(), rend = transferSpeeds.crend(); rit != rend; ++rit) {
+ PeerWireClient *client = rit->second;
bool interested = (client->peerWireState() & PeerWireClient::PeerIsInterested);
if (maxUploaders) {
@@ -1484,30 +1486,26 @@ void TorrentClient::addToPeerList(const QList<TorrentPeer> &peerList)
// of the peers that have no (or low) activity.
int maxPeers = ConnectionManager::instance()->maxConnections() * 3;
if (d->peers.size() > maxPeers) {
+ auto tooMany = d->peers.size() - maxPeers;
+
// Find what peers are currently connected & active
- QSet<TorrentPeer *> activePeers;
- for (TorrentPeer *peer : qAsConst(d->peers)) {
+ const auto firstNInactivePeers = [&tooMany, this] (TorrentPeer *peer) {
+ if (!tooMany)
+ return false;
for (const PeerWireClient *client : qAsConst(d->connections)) {
if (client->peer() == peer && (client->downloadSpeed() + client->uploadSpeed()) > 1024)
- activePeers << peer;
+ return false;
}
- }
-
+ --tooMany;
+ return true;
+ };
// Remove inactive peers from the peer list until we're below
// the max connections count.
- QList<int> toRemove;
- for (int i = 0; i < d->peers.size() && (d->peers.size() - toRemove.size()) > maxPeers; ++i) {
- if (!activePeers.contains(d->peers.at(i)))
- toRemove << i;
- }
- QListIterator<int> toRemoveIterator(toRemove);
- toRemoveIterator.toBack();
- while (toRemoveIterator.hasPrevious())
- d->peers.removeAt(toRemoveIterator.previous());
-
+ d->peers.erase(std::remove_if(d->peers.begin(), d->peers.end(),
+ firstNInactivePeers),
+ d->peers.end());
// If we still have too many peers, remove the oldest ones.
- while (d->peers.size() > maxPeers)
- d->peers.takeFirst();
+ d->peers.erase(d->peers.begin(), d->peers.begin() + tooMany);
}
if (d->state != Paused && d->state != Stopping && d->state != Idle) {
diff --git a/examples/opengl/contextinfo/widget.cpp b/examples/opengl/contextinfo/widget.cpp
index b1b7076503..0762c91662 100644
--- a/examples/opengl/contextinfo/widget.cpp
+++ b/examples/opengl/contextinfo/widget.cpp
@@ -384,7 +384,7 @@ void Widget::renderWindowReady()
m_output->append(tr("Qt OpenGL library handle: %1")
.arg(QString::number(qintptr(QOpenGLContext::openGLModuleHandle()), 16)));
- QList<QByteArray> extensionList = context->extensions().toList();
+ QList<QByteArray> extensionList = context->extensions().values();
std::sort(extensionList.begin(), extensionList.end());
m_extensions->append(tr("Found %1 extensions:").arg(extensionList.count()));
for (const QByteArray &ext : qAsConst(extensionList))
diff --git a/examples/opengl/legacy/overpainting/glwidget.cpp b/examples/opengl/legacy/overpainting/glwidget.cpp
index f98d043c5c..0094f8ead7 100644
--- a/examples/opengl/legacy/overpainting/glwidget.cpp
+++ b/examples/opengl/legacy/overpainting/glwidget.cpp
@@ -247,12 +247,8 @@ void GLWidget::createBubbles(int number)
//! [13]
void GLWidget::animate()
{
- QMutableListIterator<Bubble*> iter(bubbles);
-
- while (iter.hasNext()) {
- Bubble *bubble = iter.next();
+ for (Bubble *bubble : qAsConst(bubbles))
bubble->move(rect());
- }
update();
}
//! [13]
diff --git a/examples/opengl/qopenglwidget/glwidget.cpp b/examples/opengl/qopenglwidget/glwidget.cpp
index 946b2bec67..5057291f12 100644
--- a/examples/opengl/qopenglwidget/glwidget.cpp
+++ b/examples/opengl/qopenglwidget/glwidget.cpp
@@ -399,12 +399,9 @@ void GLWidget::paintGL()
painter.end();
- QMutableListIterator<Bubble*> iter(m_bubbles);
-
- while (iter.hasNext()) {
- Bubble *bubble = iter.next();
+ for (Bubble *bubble : qAsConst(m_bubbles))
bubble->move(rect());
- }
+
if (!(m_frames % 100)) {
m_time.start();
m_frames = 0;
diff --git a/examples/opengl/qopenglwidget/glwidget.h b/examples/opengl/qopenglwidget/glwidget.h
index de7805a907..0ad2581cb8 100644
--- a/examples/opengl/qopenglwidget/glwidget.h
+++ b/examples/opengl/qopenglwidget/glwidget.h
@@ -56,7 +56,7 @@
#include <QOpenGLBuffer>
#include <QVector3D>
#include <QMatrix4x4>
-#include <QTime>
+#include <QElapsedTimer>
#include <QVector>
#include <QPushButton>
@@ -106,7 +106,7 @@ private:
bool m_qtLogo;
QList<Bubble *> m_bubbles;
int m_frames;
- QTime m_time;
+ QElapsedTimer m_time;
QOpenGLShader *m_vshader1;
QOpenGLShader *m_fshader1;
QOpenGLShader *m_vshader2;
diff --git a/examples/opengl/threadedqopenglwidget/main.cpp b/examples/opengl/threadedqopenglwidget/main.cpp
index b9e491040f..983f608543 100644
--- a/examples/opengl/threadedqopenglwidget/main.cpp
+++ b/examples/opengl/threadedqopenglwidget/main.cpp
@@ -58,6 +58,8 @@
#include "mainwindow.h"
#include "glwidget.h"
+#include <memory>
+
static QString getGlString(QOpenGLFunctions *functions, GLenum name)
{
if (const GLubyte *p = functions->glGetString(name))
@@ -104,8 +106,8 @@ int main( int argc, char ** argv )
const QString toolTip = supportsThreading ? glInfo : glInfo + QStringLiteral("\ndoes not support threaded OpenGL.");
topLevelGlWidget.setToolTip(toolTip);
- QScopedPointer<MainWindow> mw1;
- QScopedPointer<MainWindow> mw2;
+ std::unique_ptr<MainWindow> mw1;
+ std::unique_ptr<MainWindow> mw2;
if (!parser.isSet(singleOption)) {
if (supportsThreading) {
pos += QPoint(100, 100);
diff --git a/examples/qtconcurrent/wordcount/main.cpp b/examples/qtconcurrent/wordcount/main.cpp
index ff7ea24ee7..ae8542a761 100644
--- a/examples/qtconcurrent/wordcount/main.cpp
+++ b/examples/qtconcurrent/wordcount/main.cpp
@@ -54,7 +54,7 @@
#include <QString>
#include <QStringList>
#include <QDir>
-#include <QTime>
+#include <QElapsedTimer>
#include <QApplication>
#include <QDebug>
@@ -126,11 +126,8 @@ WordCount countWords(const QString &file)
// at a time.
void reduce(WordCount &result, const WordCount &w)
{
- QMapIterator<QString, int> i(w);
- while (i.hasNext()) {
- i.next();
+ for (auto i = w.begin(), end = w.end(); i != end; ++i)
result[i.key()] += i.value();
- }
}
int main(int argc, char** argv)
@@ -149,19 +146,19 @@ int main(int argc, char** argv)
int singleThreadTime = 0;
{
- QTime time;
- time.start();
+ QElapsedTimer timer;
+ timer.start();
WordCount total = singleThreadedWordCount(files);
- singleThreadTime = time.elapsed();
+ singleThreadTime = timer.elapsed();
qDebug() << "single thread" << singleThreadTime;
}
int mapReduceTime = 0;
{
- QTime time;
- time.start();
+ QElapsedTimer timer;
+ timer.start();
WordCount total = mappedReduced(files, countWords, reduce);
- mapReduceTime = time.elapsed();
+ mapReduceTime = timer.elapsed();
qDebug() << "MapReduce" << mapReduceTime;
}
qDebug() << "MapReduce speedup x" << ((double)singleThreadTime - (double)mapReduceTime) / (double)mapReduceTime + 1;
diff --git a/examples/sql/relationaltablemodel/relationaltablemodel.cpp b/examples/sql/relationaltablemodel/relationaltablemodel.cpp
index c3c7d48d70..df4eae6e6e 100644
--- a/examples/sql/relationaltablemodel/relationaltablemodel.cpp
+++ b/examples/sql/relationaltablemodel/relationaltablemodel.cpp
@@ -53,6 +53,8 @@
#include "../connection.h"
+#include <memory>
+
void initializeModel(QSqlRelationalTableModel *model)
{
//! [0]
@@ -76,12 +78,12 @@ void initializeModel(QSqlRelationalTableModel *model)
model->select();
}
-QTableView *createView(const QString &title, QSqlTableModel *model)
+std::unique_ptr<QTableView> createView(const QString &title, QSqlTableModel *model)
{
//! [4]
- QTableView *view = new QTableView;
+ std::unique_ptr<QTableView> view{new QTableView};
view->setModel(model);
- view->setItemDelegate(new QSqlRelationalDelegate(view));
+ view->setItemDelegate(new QSqlRelationalDelegate(view.get()));
//! [4]
view->setWindowTitle(title);
return view;
@@ -118,7 +120,7 @@ int main(int argc, char *argv[])
initializeModel(&model);
- QScopedPointer<QTableView> view(createView(QObject::tr("Relational Table Model"), &model));
+ std::unique_ptr<QTableView> view = createView(QObject::tr("Relational Table Model"), &model);
view->show();
return app.exec();
diff --git a/examples/vulkan/hellovulkancubes/renderer.cpp b/examples/vulkan/hellovulkancubes/renderer.cpp
index 5ada79ce79..f104d79002 100644
--- a/examples/vulkan/hellovulkancubes/renderer.cpp
+++ b/examples/vulkan/hellovulkancubes/renderer.cpp
@@ -49,6 +49,7 @@
****************************************************************************/
#include "renderer.h"
+#include "qrandom.h"
#include <QVulkanFunctions>
#include <QtConcurrentRun>
#include <QTime>
@@ -77,8 +78,6 @@ Renderer::Renderer(VulkanWindow *w, int initialCount)
m_cam(QVector3D(0.0f, 0.0f, 20.0f)), // starting camera position
m_instCount(initialCount)
{
- qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
-
m_floorModel.translate(0, -5, 0);
m_floorModel.rotate(-90, 1, 0, 0);
m_floorModel.scale(20, 100, 1);
@@ -793,7 +792,9 @@ void Renderer::ensureInstanceBuffer()
qDebug("Preparing instances %d..%d", m_preparedInstCount, m_instCount - 1);
char *p = m_instData.data();
p += m_preparedInstCount * PER_INSTANCE_DATA_SIZE;
- auto gen = [](float a, float b) { return float((qrand() % int(b - a + 1)) + a); };
+ auto gen = [](int a, int b) {
+ return float(QRandomGenerator::global()->bounded(double(b - a)) + a);
+ };
for (int i = m_preparedInstCount; i < m_instCount; ++i) {
// Apply a random translation to each instance of the mesh.
float t[] = { gen(-5, 5), gen(-4, 6), gen(-30, 5) };
diff --git a/examples/vulkan/hellovulkanwidget/hellovulkanwidget.cpp b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.cpp
index 81daa9bb96..cf95a0e6a0 100644
--- a/examples/vulkan/hellovulkanwidget/hellovulkanwidget.cpp
+++ b/examples/vulkan/hellovulkanwidget/hellovulkanwidget.cpp
@@ -140,12 +140,12 @@ void VulkanRenderer::initResources()
m_devFuncs = inst->deviceFunctions(m_window->device());
QString info;
- info += QString().sprintf("Number of physical devices: %d\n", m_window->availablePhysicalDevices().count());
+ info += QString::asprintf("Number of physical devices: %d\n", m_window->availablePhysicalDevices().count());
QVulkanFunctions *f = inst->functions();
VkPhysicalDeviceProperties props;
f->vkGetPhysicalDeviceProperties(m_window->physicalDevice(), &props);
- info += QString().sprintf("Active physical device name: '%s' version %d.%d.%d\nAPI version %d.%d.%d\n",
+ info += QString::asprintf("Active physical device name: '%s' version %d.%d.%d\nAPI version %d.%d.%d\n",
props.deviceName,
VK_VERSION_MAJOR(props.driverVersion), VK_VERSION_MINOR(props.driverVersion),
VK_VERSION_PATCH(props.driverVersion),
@@ -154,19 +154,19 @@ void VulkanRenderer::initResources()
info += QStringLiteral("Supported instance layers:\n");
for (const QVulkanLayer &layer : inst->supportedLayers())
- info += QString().sprintf(" %s v%u\n", layer.name.constData(), layer.version);
+ info += QString::asprintf(" %s v%u\n", layer.name.constData(), layer.version);
info += QStringLiteral("Enabled instance layers:\n");
for (const QByteArray &layer : inst->layers())
- info += QString().sprintf(" %s\n", layer.constData());
+ info += QString::asprintf(" %s\n", layer.constData());
info += QStringLiteral("Supported instance extensions:\n");
for (const QVulkanExtension &ext : inst->supportedExtensions())
- info += QString().sprintf(" %s v%u\n", ext.name.constData(), ext.version);
+ info += QString::asprintf(" %s v%u\n", ext.name.constData(), ext.version);
info += QStringLiteral("Enabled instance extensions:\n");
for (const QByteArray &ext : inst->extensions())
- info += QString().sprintf(" %s\n", ext.constData());
+ info += QString::asprintf(" %s\n", ext.constData());
- info += QString().sprintf("Color format: %u\nDepth-stencil format: %u\n",
+ info += QString::asprintf("Color format: %u\nDepth-stencil format: %u\n",
m_window->colorFormat(), m_window->depthStencilFormat());
info += QStringLiteral("Supported sample counts:");
diff --git a/examples/widgets/dialogs/standarddialogs/dialog.cpp b/examples/widgets/dialogs/standarddialogs/dialog.cpp
index 1830b21e8f..c91a594490 100644
--- a/examples/widgets/dialogs/standarddialogs/dialog.cpp
+++ b/examples/widgets/dialogs/standarddialogs/dialog.cpp
@@ -287,7 +287,6 @@ Dialog::Dialog(QWidget *parent)
fileDialogOptionsWidget->addCheckBox(tr("Show directories only"), QFileDialog::ShowDirsOnly);
fileDialogOptionsWidget->addCheckBox(tr("Do not resolve symlinks"), QFileDialog::DontResolveSymlinks);
fileDialogOptionsWidget->addCheckBox(tr("Do not confirm overwrite"), QFileDialog::DontConfirmOverwrite);
- fileDialogOptionsWidget->addCheckBox(tr("Do not use sheet"), QFileDialog::DontUseSheet);
fileDialogOptionsWidget->addCheckBox(tr("Readonly"), QFileDialog::ReadOnly);
fileDialogOptionsWidget->addCheckBox(tr("Hide name filter details"), QFileDialog::HideNameFilterDetails);
fileDialogOptionsWidget->addCheckBox(tr("Do not use custom directory icons (Windows)"), QFileDialog::DontUseCustomDirectoryIcons);
diff --git a/examples/widgets/doc/src/application.qdoc b/examples/widgets/doc/src/application.qdoc
index 040aa171b7..6c37fa67bb 100644
--- a/examples/widgets/doc/src/application.qdoc
+++ b/examples/widgets/doc/src/application.qdoc
@@ -327,9 +327,12 @@
\snippet mainwindows/application/mainwindow.cpp 44
\snippet mainwindows/application/mainwindow.cpp 45
- Saving a file is very similar to loading one. Here, the
- QFile::Text flag ensures that on Windows, "\\n" is converted into
- "\\r\\n" to conform to the Windows convension.
+ Saving a file is similar to loading one. We use QSaveFile to ensure
+ all data are safely written and existing files are not damaged
+ should writing fail.
+ We use the QFile::Text flag to make sure that on Windows, "\\n"
+ is converted into "\\r\\n" to conform to the Windows convention.
+
\snippet mainwindows/application/mainwindow.cpp 46
\snippet mainwindows/application/mainwindow.cpp 47
diff --git a/examples/widgets/doc/src/icons.qdoc b/examples/widgets/doc/src/icons.qdoc
index 60cb9062c2..7aae0491d6 100644
--- a/examples/widgets/doc/src/icons.qdoc
+++ b/examples/widgets/doc/src/icons.qdoc
@@ -262,12 +262,7 @@
provides arrays allowing to map from enumeration value to row/column
(by using QVector::indexOf()) and back by using the array index and lists
of the matching strings. Qt's containers can be easily populated by
- using C++ 11 initializer lists. If the compiler does not provide that feature,
- a pattern like
-
- \snippet widgets/icons/iconpreviewarea.cpp 43
-
- can be used.
+ using C++ 11 initializer lists.
We need two public functions to set the current icon and the
icon's size. In addition the class has three private functions: We
diff --git a/examples/widgets/graphicsview/boxes/scene.cpp b/examples/widgets/graphicsview/boxes/scene.cpp
index 7f62ac894b..d51124aed7 100644
--- a/examples/widgets/graphicsview/boxes/scene.cpp
+++ b/examples/widgets/graphicsview/boxes/scene.cpp
@@ -533,8 +533,6 @@ Scene::Scene(int width, int height, int maxTextureSize)
m_timer->setInterval(20);
connect(m_timer, &QTimer::timeout, this, [this](){ update(); });
m_timer->start();
-
- m_time.start();
}
Scene::~Scene()
diff --git a/examples/widgets/graphicsview/boxes/scene.h b/examples/widgets/graphicsview/boxes/scene.h
index ccb6f368cd..ffff01358f 100644
--- a/examples/widgets/graphicsview/boxes/scene.h
+++ b/examples/widgets/graphicsview/boxes/scene.h
@@ -220,7 +220,7 @@ private:
void initGL();
QPointF pixelPosToViewPos(const QPointF& p);
- QTime m_time;
+ QTime m_time; // ### Qt 6: remove (unused)
int m_lastTime;
int m_mouseEventTime;
int m_distExp;
diff --git a/examples/widgets/graphicsview/diagramscene/arrow.cpp b/examples/widgets/graphicsview/diagramscene/arrow.cpp
index 88160d9399..525e0b3fbb 100644
--- a/examples/widgets/graphicsview/diagramscene/arrow.cpp
+++ b/examples/widgets/graphicsview/diagramscene/arrow.cpp
@@ -113,15 +113,13 @@ void Arrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *,
QLineF centerLine(myStartItem->pos(), myEndItem->pos());
QPolygonF endPolygon = myEndItem->polygon();
QPointF p1 = endPolygon.first() + myEndItem->pos();
- QPointF p2;
QPointF intersectPoint;
- QLineF polyLine;
for (int i = 1; i < endPolygon.count(); ++i) {
- p2 = endPolygon.at(i) + myEndItem->pos();
- polyLine = QLineF(p1, p2);
- QLineF::IntersectType intersectType =
- polyLine.intersect(centerLine, &intersectPoint);
- if (intersectType == QLineF::BoundedIntersection)
+ QPointF p2 = endPolygon.at(i) + myEndItem->pos();
+ QLineF polyLine = QLineF(p1, p2);
+ QLineF::IntersectionType intersectionType =
+ polyLine.intersects(centerLine, &intersectPoint);
+ if (intersectionType == QLineF::BoundedIntersection)
break;
p1 = p2;
}
diff --git a/examples/widgets/graphicsview/diagramscene/mainwindow.cpp b/examples/widgets/graphicsview/diagramscene/mainwindow.cpp
index 07f92f61c1..3327d4d5df 100644
--- a/examples/widgets/graphicsview/diagramscene/mainwindow.cpp
+++ b/examples/widgets/graphicsview/diagramscene/mainwindow.cpp
@@ -473,7 +473,7 @@ void MainWindow::createToolbars()
fontSizeCombo->addItem(QString().setNum(i));
QIntValidator *validator = new QIntValidator(2, 64, this);
fontSizeCombo->setValidator(validator);
- connect(fontSizeCombo, QOverload<const QString &>::of(&QComboBox::currentIndexChanged),
+ connect(fontSizeCombo, &QComboBox::currentTextChanged,
this, &MainWindow::fontSizeChanged);
fontColorToolButton = new QToolButton;
@@ -536,7 +536,7 @@ void MainWindow::createToolbars()
scales << tr("50%") << tr("75%") << tr("100%") << tr("125%") << tr("150%");
sceneScaleCombo->addItems(scales);
sceneScaleCombo->setCurrentIndex(2);
- connect(sceneScaleCombo, QOverload<const QString &>::of(&QComboBox::currentIndexChanged),
+ connect(sceneScaleCombo, &QComboBox::currentTextChanged,
this, &MainWindow::sceneScaleChanged);
pointerToolbar = addToolBar(tr("Pointer type"));
diff --git a/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp
index 0c831360cf..9fa24fcd17 100644
--- a/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp
+++ b/examples/widgets/graphicsview/embeddeddialogs/embeddeddialog.cpp
@@ -73,7 +73,7 @@ EmbeddedDialog::EmbeddedDialog(QWidget *parent)
this, &EmbeddedDialog::spacingChanged);
connect(ui->fontComboBox, &QFontComboBox::currentFontChanged,
this, &EmbeddedDialog::fontChanged);
- connect(ui->style, QOverload<const QString &>::of(&QComboBox::activated),
+ connect(ui->style, &QComboBox::textActivated,
this, &EmbeddedDialog::styleChanged);
}
diff --git a/examples/widgets/mainwindows/application/mainwindow.cpp b/examples/widgets/mainwindows/application/mainwindow.cpp
index 4b639ead18..7886c4afac 100644
--- a/examples/widgets/mainwindows/application/mainwindow.cpp
+++ b/examples/widgets/mainwindows/application/mainwindow.cpp
@@ -353,23 +353,27 @@ void MainWindow::loadFile(const QString &fileName)
bool MainWindow::saveFile(const QString &fileName)
//! [44] //! [45]
{
- QFile file(fileName);
- if (!file.open(QFile::WriteOnly | QFile::Text)) {
- QMessageBox::warning(this, tr("Application"),
- tr("Cannot write file %1:\n%2.")
- .arg(QDir::toNativeSeparators(fileName),
- file.errorString()));
- return false;
- }
+ QString errorMessage;
- QTextStream out(&file);
-#ifndef QT_NO_CURSOR
QGuiApplication::setOverrideCursor(Qt::WaitCursor);
-#endif
- out << textEdit->toPlainText();
-#ifndef QT_NO_CURSOR
+ QSaveFile file(fileName);
+ if (file.open(QFile::WriteOnly | QFile::Text)) {
+ QTextStream out(&file);
+ out << textEdit->toPlainText();
+ if (!file.commit()) {
+ errorMessage = tr("Cannot write file %1:\n%2.")
+ .arg(QDir::toNativeSeparators(fileName), file.errorString());
+ }
+ } else {
+ errorMessage = tr("Cannot open file %1 for writing:\n%2.")
+ .arg(QDir::toNativeSeparators(fileName), file.errorString());
+ }
QGuiApplication::restoreOverrideCursor();
-#endif
+
+ if (!errorMessage.isEmpty()) {
+ QMessageBox::warning(this, tr("Application"), errorMessage);
+ return false;
+ }
setCurrentFile(fileName);
statusBar()->showMessage(tr("File saved"), 2000);
diff --git a/examples/widgets/mainwindows/mdi/mdichild.cpp b/examples/widgets/mainwindows/mdi/mdichild.cpp
index 16f2040de0..727d4f6cfd 100644
--- a/examples/widgets/mainwindows/mdi/mdichild.cpp
+++ b/examples/widgets/mainwindows/mdi/mdichild.cpp
@@ -115,19 +115,28 @@ bool MdiChild::saveAs()
bool MdiChild::saveFile(const QString &fileName)
{
- QFile file(fileName);
- if (!file.open(QFile::WriteOnly | QFile::Text)) {
- QMessageBox::warning(this, tr("MDI"),
- tr("Cannot write file %1:\n%2.")
- .arg(QDir::toNativeSeparators(fileName), file.errorString()));
- return false;
- }
+ QString errorMessage;
- QTextStream out(&file);
QGuiApplication::setOverrideCursor(Qt::WaitCursor);
- out << toPlainText();
+ QSaveFile file(fileName);
+ if (file.open(QFile::WriteOnly | QFile::Text)) {
+ QTextStream out(&file);
+ out << toPlainText();
+ if (!file.commit()) {
+ errorMessage = tr("Cannot write file %1:\n%2.")
+ .arg(QDir::toNativeSeparators(fileName), file.errorString());
+ }
+ } else {
+ errorMessage = tr("Cannot open file %1 for writing:\n%2.")
+ .arg(QDir::toNativeSeparators(fileName), file.errorString());
+ }
QGuiApplication::restoreOverrideCursor();
+ if (!errorMessage.isEmpty()) {
+ QMessageBox::warning(this, tr("MDI"), errorMessage);
+ return false;
+ }
+
setCurrentFile(fileName);
return true;
}
diff --git a/examples/widgets/mainwindows/sdi/mainwindow.cpp b/examples/widgets/mainwindows/sdi/mainwindow.cpp
index 62a74b26e6..a1fb42158e 100644
--- a/examples/widgets/mainwindows/sdi/mainwindow.cpp
+++ b/examples/widgets/mainwindows/sdi/mainwindow.cpp
@@ -425,19 +425,28 @@ void MainWindow::openRecentFile()
bool MainWindow::saveFile(const QString &fileName)
{
- QFile file(fileName);
- if (!file.open(QFile::WriteOnly | QFile::Text)) {
- QMessageBox::warning(this, tr("SDI"),
- tr("Cannot write file %1:\n%2.")
- .arg(QDir::toNativeSeparators(fileName), file.errorString()));
- return false;
- }
+ QString errorMessage;
- QTextStream out(&file);
QGuiApplication::setOverrideCursor(Qt::WaitCursor);
- out << textEdit->toPlainText();
+ QSaveFile file(fileName);
+ if (file.open(QFile::WriteOnly | QFile::Text)) {
+ QTextStream out(&file);
+ out << textEdit->toPlainText();
+ if (!file.commit()) {
+ errorMessage = tr("Cannot write file %1:\n%2.")
+ .arg(QDir::toNativeSeparators(fileName), file.errorString());
+ }
+ } else {
+ errorMessage = tr("Cannot open file %1 for writing:\n%2.")
+ .arg(QDir::toNativeSeparators(fileName), file.errorString());
+ }
QGuiApplication::restoreOverrideCursor();
+ if (!errorMessage.isEmpty()) {
+ QMessageBox::warning(this, tr("SDI"), errorMessage);
+ return false;
+ }
+
setCurrentFile(fileName);
statusBar()->showMessage(tr("File saved"), 2000);
return true;
diff --git a/examples/widgets/painting/affine/xform.cpp b/examples/widgets/painting/affine/xform.cpp
index dc01acf453..482e0f3268 100644
--- a/examples/widgets/painting/affine/xform.cpp
+++ b/examples/widgets/painting/affine/xform.cpp
@@ -160,10 +160,7 @@ void XFormView::updateCtrlPoints(const QPolygonF &points)
ctrlPoints = points;
QLineF line(ctrlPoints.at(0), ctrlPoints.at(1));
- m_rotation = line.angle(QLineF(0, 0, 1, 0));
- if (line.dy() < 0)
- m_rotation = 360 - m_rotation;
-
+ m_rotation = 360 - QLineF(0, 0, 1, 0).angleTo(line);
if (trans.isNull())
emit rotationChanged(int(m_rotation*10));
}
diff --git a/examples/widgets/painting/composition/composition.cpp b/examples/widgets/painting/composition/composition.cpp
index 9bd71735a0..a220fb42fa 100644
--- a/examples/widgets/painting/composition/composition.cpp
+++ b/examples/widgets/painting/composition/composition.cpp
@@ -224,6 +224,10 @@ CompositionWidget::CompositionWidget(QWidget *parent)
setWindowTitle(tr("Composition Modes"));
}
+CompositionWidget::~CompositionWidget()
+{
+}
+
void CompositionWidget::nextMode()
{
@@ -265,6 +269,10 @@ CompositionRenderer::CompositionRenderer(QWidget *parent)
#endif
}
+CompositionRenderer::~CompositionRenderer()
+{
+}
+
QRectF rectangle_around(const QPointF &p, const QSizeF &size = QSize(250, 200))
{
QRectF rect(p, size);
@@ -371,7 +379,7 @@ void CompositionRenderer::paint(QPainter *painter)
if (size() != m_previous_size) {
m_previous_size = size();
- QPainter p(m_fbo.data());
+ QPainter p(m_fbo.get());
p.setCompositionMode(QPainter::CompositionMode_Source);
p.fillRect(QRect(QPoint(0, 0), size()), Qt::transparent);
p.setCompositionMode(QPainter::CompositionMode_SourceOver);
@@ -382,7 +390,7 @@ void CompositionRenderer::paint(QPainter *painter)
painter->beginNativePainting();
{
- QPainter p(m_fbo.data());
+ QPainter p(m_fbo.get());
p.beginNativePainting();
m_blitter.bind();
const QRect targetRect(QPoint(0, 0), m_fbo->size());
diff --git a/examples/widgets/painting/composition/composition.h b/examples/widgets/painting/composition/composition.h
index 19150e2024..52ca7919b0 100644
--- a/examples/widgets/painting/composition/composition.h
+++ b/examples/widgets/painting/composition/composition.h
@@ -61,6 +61,8 @@
#include <QPainter>
#include <QEvent>
+#include <memory>
+
QT_BEGIN_NAMESPACE
class QPushButton;
class QRadioButton;
@@ -71,7 +73,8 @@ class CompositionWidget : public QWidget
Q_OBJECT
public:
- CompositionWidget(QWidget *parent);
+ explicit CompositionWidget(QWidget *parent = nullptr);
+ ~CompositionWidget();
public slots:
void nextMode();
@@ -117,7 +120,8 @@ class CompositionRenderer : public ArthurFrame
Q_PROPERTY(bool animation READ animationEnabled WRITE setAnimationEnabled)
public:
- CompositionRenderer(QWidget *parent);
+ explicit CompositionRenderer(QWidget *parent = nullptr);
+ ~CompositionRenderer();
void paint(QPainter *) override;
@@ -188,7 +192,7 @@ private:
int m_animationTimer;
#if QT_CONFIG(opengl)
- QScopedPointer<QFboPaintDevice> m_fbo;
+ std::unique_ptr<QFboPaintDevice> m_fbo;
int m_pbuffer_size; // width==height==size of pbuffer
uint m_base_tex;
uint m_compositing_tex;
diff --git a/examples/widgets/painting/composition/main.cpp b/examples/widgets/painting/composition/main.cpp
index 2eaeaba2c5..1ffa29dddc 100644
--- a/examples/widgets/painting/composition/main.cpp
+++ b/examples/widgets/painting/composition/main.cpp
@@ -56,13 +56,13 @@ int main(int argc, char *argv[])
{
QApplication app(argc, argv);
+ QScopedPointer<QStyle> arthurStyle(new ArthurStyle());
CompositionWidget compWidget(nullptr);
- QStyle *arthurStyle = new ArthurStyle();
- compWidget.setStyle(arthurStyle);
+ compWidget.setStyle(arthurStyle.data());
const QList<QWidget *> widgets = compWidget.findChildren<QWidget *>();
for (QWidget *w : widgets)
- w->setStyle(arthurStyle);
+ w->setStyle(arthurStyle.data());
compWidget.show();
return app.exec();
diff --git a/examples/widgets/painting/deform/pathdeform.h b/examples/widgets/painting/deform/pathdeform.h
index b7c7386e2a..af869badc9 100644
--- a/examples/widgets/painting/deform/pathdeform.h
+++ b/examples/widgets/painting/deform/pathdeform.h
@@ -54,7 +54,7 @@
#include "arthurwidgets.h"
#include <QBasicTimer>
-#include <QDateTime>
+#include <QElapsedTimer>
#include <QPainterPath>
class PathDeformRenderer : public ArthurFrame
@@ -103,7 +103,7 @@ private:
QBasicTimer m_repaintTimer;
// QBasicTimer m_fpsTimer;
// int m_fpsCounter;
- QTime m_repaintTracker;
+ QElapsedTimer m_repaintTracker;
QVector<QPainterPath> m_paths;
QVector<QPointF> m_advances;
diff --git a/examples/widgets/painting/gradients/gradients.cpp b/examples/widgets/painting/gradients/gradients.cpp
index 7abaef771b..a4528ce06f 100644
--- a/examples/widgets/painting/gradients/gradients.cpp
+++ b/examples/widgets/painting/gradients/gradients.cpp
@@ -72,7 +72,7 @@ ShadeWidget::ShadeWidget(ShadeType type, QWidget *parent)
setPalette(pal);
} else {
- setAttribute(Qt::WA_NoBackground);
+ setAttribute(Qt::WA_OpaquePaintEvent);
}
QPolygonF points;
@@ -564,9 +564,7 @@ void GradientRenderer::paint(QPainter *p)
} else {
QLineF l(pts.at(0), pts.at(1));
- qreal angle = l.angle(QLineF(0, 0, 1, 0));
- if (l.dy() > 0)
- angle = 360 - angle;
+ qreal angle = QLineF(0, 0, 1, 0).angleTo(l);
g = QConicalGradient(pts.at(0), angle);
}
diff --git a/examples/widgets/painting/pathstroke/pathstroke.cpp b/examples/widgets/painting/pathstroke/pathstroke.cpp
index 03e55bb2a2..e4009f0b1a 100644
--- a/examples/widgets/painting/pathstroke/pathstroke.cpp
+++ b/examples/widgets/painting/pathstroke/pathstroke.cpp
@@ -611,7 +611,8 @@ bool PathStrokeRenderer::event(QEvent *e)
case Qt::TouchPointPressed:
{
// find the point, move it
- QSet<int> activePoints = QSet<int>::fromList(m_fingerPointMapping.values());
+ const auto mappedPoints = m_fingerPointMapping.values();
+ QSet<int> activePoints = QSet<int>(mappedPoints.begin(), mappedPoints.end());
int activePoint = -1;
qreal distance = -1;
const int pointsCount = m_points.size();
diff --git a/examples/widgets/painting/shared/hoverpoints.cpp b/examples/widgets/painting/shared/hoverpoints.cpp
index 74c78088ad..2032fb5a2c 100644
--- a/examples/widgets/painting/shared/hoverpoints.cpp
+++ b/examples/widgets/painting/shared/hoverpoints.cpp
@@ -180,7 +180,8 @@ bool HoverPoints::eventFilter(QObject *object, QEvent *event)
case Qt::TouchPointPressed:
{
// find the point, move it
- QSet<int> activePoints = QSet<int>::fromList(m_fingerPointMapping.values());
+ const auto mappedPoints = m_fingerPointMapping.values();
+ QSet<int> activePoints = QSet<int>(mappedPoints.begin(), mappedPoints.end());
int activePoint = -1;
qreal distance = -1;
const int pointsCount = m_points.size();
diff --git a/examples/widgets/qnx/foreignwindows/collector.cpp b/examples/widgets/qnx/foreignwindows/collector.cpp
new file mode 100644
index 0000000000..4b9e774945
--- /dev/null
+++ b/examples/widgets/qnx/foreignwindows/collector.cpp
@@ -0,0 +1,176 @@
+/***************************************************************************
+**
+** Copyright (C) 2018 QNX Software Systems. All rights reserved.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** 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.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QApplication>
+#include <QDebug>
+#include <QHBoxLayout>
+#include <QWindow>
+
+#include <algorithm>
+#include <screen/screen.h>
+
+#include "collector.h"
+
+constexpr int MANAGER_EVENT_NAME_SUGGESTION = 9999;
+
+Collector::Collector(QWidget *parent)
+ : QWidget(parent)
+{
+ QApplication::instance()->installNativeEventFilter(this);
+
+ QLayout *layout = new QHBoxLayout(this);
+ setLayout(layout);
+}
+
+Collector::~Collector()
+{
+ QApplication::instance()->removeNativeEventFilter(this);
+}
+
+bool Collector::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
+{
+ Q_UNUSED(result);
+
+ if (eventType == QByteArrayLiteral("screen_event_t"))
+ return filterQnxScreenEvent(static_cast<screen_event_t>(message));
+
+ return false;
+}
+
+bool Collector::filterQnxScreenEvent(screen_event_t event)
+{
+ int objectType = SCREEN_OBJECT_TYPE_CONTEXT;
+ screen_get_event_property_iv(event, SCREEN_PROPERTY_OBJECT_TYPE, &objectType);
+
+ if (objectType == SCREEN_OBJECT_TYPE_WINDOW)
+ return filterQnxScreenWindowEvent(event);
+
+ return false;
+}
+
+bool Collector::filterQnxScreenWindowEvent(screen_event_t event)
+{
+ int eventType = SCREEN_EVENT_NONE;
+ screen_get_event_property_iv(event, SCREEN_PROPERTY_TYPE, &eventType);
+ screen_window_t window = nullptr;
+ screen_get_event_property_pv(event,
+ SCREEN_PROPERTY_WINDOW,
+ reinterpret_cast<void **>(&window));
+
+ if (eventType == SCREEN_EVENT_CREATE)
+ return filterQnxScreenWindowCreateEvent(window, event);
+ else if (eventType == SCREEN_EVENT_CLOSE)
+ return filterQnxScreenWindowCloseEvent(window, event);
+ else if (eventType == SCREEN_EVENT_MANAGER)
+ return filterQnxScreenWindowManagerEvent(window, event);
+
+ return false;
+}
+
+bool Collector::filterQnxScreenWindowCreateEvent(screen_window_t window, screen_event_t event)
+{
+ Q_UNUSED(event);
+ WId winId = reinterpret_cast<WId>(window);
+
+ QByteArray parentGroup(256, 0);
+ screen_get_window_property_cv(window,
+ SCREEN_PROPERTY_PARENT,
+ parentGroup.length(),
+ parentGroup.data());
+ parentGroup.resize(strlen(parentGroup.constData()));
+
+ QByteArray group(256, 0);
+ screen_get_window_property_cv(reinterpret_cast<screen_window_t>(windowHandle()->winId()),
+ SCREEN_PROPERTY_GROUP,
+ group.length(),
+ group.data());
+ group.resize(strlen(group.constData()));
+
+ if (parentGroup != group)
+ return false;
+
+ Collectible collectible;
+ collectible.window = QWindow::fromWinId(winId);
+ collectible.widget = QWidget::createWindowContainer(collectible.window, this);
+ layout()->addWidget(collectible.widget);
+ m_collectibles.append(collectible);
+
+ return false;
+}
+
+bool Collector::filterQnxScreenWindowCloseEvent(screen_window_t window, screen_event_t event)
+{
+ Q_UNUSED(event);
+ WId winId = reinterpret_cast<WId>(window);
+ auto it = std::find_if(m_collectibles.begin(), m_collectibles.end(),
+ [winId] (const Collectible &collectible) {
+ return collectible.window->winId() == winId;
+ });
+ if (it != m_collectibles.end()) {
+ delete it->widget;
+ // it->window is deleted by it->widget.
+ m_collectibles.erase(it);
+ }
+
+ return false;
+}
+
+bool Collector::filterQnxScreenWindowManagerEvent(screen_window_t window, screen_event_t event)
+{
+ int managerEventType = 0;
+ screen_get_event_property_iv(event, SCREEN_PROPERTY_SUBTYPE, &managerEventType);
+
+ if (managerEventType == MANAGER_EVENT_NAME_SUGGESTION)
+ return filterQnxScreenWindowManagerNameEvent(window, event);
+
+ return false;
+}
+
+bool Collector::filterQnxScreenWindowManagerNameEvent(screen_window_t window, screen_event_t event)
+{
+ Q_UNUSED(window);
+ int dataSize = 0;
+ screen_get_event_property_iv(event, SCREEN_PROPERTY_SIZE, &dataSize);
+ if (dataSize > 0) {
+ QByteArray data(dataSize, 0);
+ screen_get_event_property_cv(event, SCREEN_PROPERTY_USER_DATA, data.size(), data.data());
+ }
+
+ return false;
+}
diff --git a/examples/widgets/qnx/foreignwindows/collector.h b/examples/widgets/qnx/foreignwindows/collector.h
new file mode 100644
index 0000000000..2b1ed499ff
--- /dev/null
+++ b/examples/widgets/qnx/foreignwindows/collector.h
@@ -0,0 +1,75 @@
+/***************************************************************************
+**
+** Copyright (C) 2018 QNX Software Systems. All rights reserved.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** 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.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef COLLECTOR_H_
+#define COLLECTOR_H_
+
+#include <QAbstractNativeEventFilter>
+#include <QWidget>
+#include <QVector>
+
+#include <screen/screen.h>
+
+class Collector : public QWidget, public QAbstractNativeEventFilter
+{
+public:
+ explicit Collector(QWidget *parent = nullptr);
+ ~Collector() override;
+
+ bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) override;
+
+private:
+ struct Collectible
+ {
+ QWindow *window;
+ QWidget *widget;
+ };
+ QVector<Collectible> m_collectibles;
+
+ bool filterQnxScreenEvent(screen_event_t event);
+ bool filterQnxScreenWindowEvent(screen_event_t event);
+ bool filterQnxScreenWindowCreateEvent(screen_window_t window, screen_event_t event);
+ bool filterQnxScreenWindowCloseEvent(screen_window_t window, screen_event_t event);
+ bool filterQnxScreenWindowManagerEvent(screen_window_t window, screen_event_t event);
+ bool filterQnxScreenWindowManagerNameEvent(screen_window_t window,
+ screen_event_t event);
+};
+
+
+#endif /* COLLECTOR_H_ */
diff --git a/examples/widgets/qnx/foreignwindows/foreignwindows.pro b/examples/widgets/qnx/foreignwindows/foreignwindows.pro
new file mode 100644
index 0000000000..09ff8633eb
--- /dev/null
+++ b/examples/widgets/qnx/foreignwindows/foreignwindows.pro
@@ -0,0 +1,11 @@
+TEMPLATE = app
+
+HEADERS += collector.h
+SOURCES += main.cpp collector.cpp
+LIBS += -lscreen
+
+QT += widgets
+
+# install
+target.path = $$[QT_INSTALL_EXAMPLES]/widgets/qnx/foreignwindows
+INSTALLS += target
diff --git a/examples/widgets/qnx/foreignwindows/main.cpp b/examples/widgets/qnx/foreignwindows/main.cpp
new file mode 100644
index 0000000000..128e93cf88
--- /dev/null
+++ b/examples/widgets/qnx/foreignwindows/main.cpp
@@ -0,0 +1,53 @@
+/***************************************************************************
+**
+** Copyright (C) 2018 QNX Software Systems. All rights reserved.
+** Contact: https://www.qt.io/licensing/
+**
+** This file is part of the plugins of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** 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.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 3 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL3 included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 3 requirements
+** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 2.0 or (at your option) the GNU General
+** Public license version 3 or any later version approved by the KDE Free
+** Qt Foundation. The licenses are as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
+** included in the packaging of this file. Please review the following
+** information to ensure the GNU General Public License requirements will
+** be met: https://www.gnu.org/licenses/gpl-2.0.html and
+** https://www.gnu.org/licenses/gpl-3.0.html.
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#include <QApplication>
+
+#include "collector.h"
+
+int main(int argc, char *argv[])
+{
+ QApplication app(argc, argv);
+
+ Collector collector;
+ collector.resize(640, 480);
+ collector.show();
+
+ return app.exec();
+}
diff --git a/examples/widgets/richtext/textedit/example.md b/examples/widgets/richtext/textedit/example.md
new file mode 100644
index 0000000000..a16a9197b4
--- /dev/null
+++ b/examples/widgets/richtext/textedit/example.md
@@ -0,0 +1,102 @@
+# QTextEdit
+
+The QTextEdit widget is an advanced editor that supports formatted rich text.
+It can be used to display HTML and other rich document formats. Internally,
+QTextEdit uses the QTextDocument class to describe both the high-level
+structure of each document and the low-level formatting of paragraphs.
+
+If you are viewing this document in the textedit example, you can edit this
+document to explore Qt's rich text editing features. We have included some
+comments in each of the following sections to encourage you to experiment.
+
+## Font and Paragraph Styles
+
+QTextEdit supports **bold**, *italic*, &amp; ~~strikethrough~~ font styles, and
+can display <span style="font-size:10pt; font-weight:600;
+color:#00007f;">multicolored</span> text. Font families such as <span
+style="font-family:Times New Roman">Times New Roman</span> and `Courier`
+can also be used directly. *If you place the cursor in a region of styled text,
+the controls in the tool bars will change to reflect the current style.*
+
+Paragraphs can be formatted so that the text is left-aligned, right-aligned,
+centered, or fully justified.
+
+*Try changing the alignment of some text and resize the editor to see how the
+text layout changes.*
+
+## Lists
+
+Different kinds of lists can be included in rich text documents. Standard
+bullet lists can be nested, using different symbols for each level of the list:
+
+- Disc symbols are typically used for top-level list items.
+ * Circle symbols can be used to distinguish between items in lower-level
+ lists.
+ + Square symbols provide a reasonable alternative to discs and circles.
+
+Ordered lists can be created that can be used for tables of contents. Different
+characters can be used to enumerate items, and we can use both Roman and Arabic
+numerals in the same list structure:
+
+1. Introduction
+2. Qt Tools
+ 1) Qt Assistant
+ 2) Qt Designer
+ 1. Form Editor
+ 2. Component Architecture
+ 3) Qt Linguist
+
+The list will automatically be renumbered if you add or remove items. *Try
+adding new sections to the above list or removing existing item to see the
+numbers change.*
+
+Task lists can be used to track progress on projects:
+
+- [ ] This is not yet done
+- This is just a bullet point
+- [x] This is done
+
+## Images
+
+Inline images are treated like ordinary ranges of characters in the text
+editor, so they flow with the surrounding text. Images can also be selected in
+the same way as text, making it easy to cut, copy, and paste them.
+
+![logo](images/logo32.png "logo") *Try to select this image by clicking and
+dragging over it with the mouse, or use the text cursor to select it by holding
+down Shift and using the arrow keys. You can then cut or copy it, and paste it
+into different parts of this document.*
+
+## Tables
+
+QTextEdit can arrange and format tables, supporting features such as row and
+column spans, text formatting within cells, and size constraints for columns.
+
+| | Development Tools | Programming Techniques | Graphical User Interfaces |
+| ------------: | ----------------- | ---------------------- | ------------------------- |
+| 9:00 - 11:00 | Introduction to Qt |||
+| 11:00 - 13:00 | Using qmake | Object-oriented Programming | Layouts in Qt |
+| 13:00 - 15:00 | Qt Designer Tutorial | Extreme Programming | Writing Custom Styles |
+| 15:00 - 17:00 | Qt Linguist and Internationalization | &nbsp; | &nbsp; |
+
+*Try adding text to the cells in the table and experiment with the alignment of
+the paragraphs.*
+
+## Hyperlinks
+
+QTextEdit is designed to support hyperlinks between documents, and this feature
+is used extensively in
+[Qt Assistant](http://doc.qt.io/qt-5/qtassistant-index.html). Hyperlinks are
+automatically created when an HTML file is imported into an editor. Since the
+rich text framework supports hyperlinks natively, they can also be created
+programatically.
+
+## Undo and Redo
+
+Full support for undo and redo operations is built into QTextEdit and the
+underlying rich text framework. Operations on a document can be packaged
+together to make editing a more comfortable experience for the user.
+
+*Try making changes to this document and press `Ctrl+Z` to undo them. You can
+always recover the original contents of the document.*
+
diff --git a/examples/widgets/richtext/textedit/images/mac/checkbox-checked.png b/examples/widgets/richtext/textedit/images/mac/checkbox-checked.png
new file mode 100644
index 0000000000..a072d7fb5c
--- /dev/null
+++ b/examples/widgets/richtext/textedit/images/mac/checkbox-checked.png
Binary files differ
diff --git a/examples/widgets/richtext/textedit/images/mac/checkbox.png b/examples/widgets/richtext/textedit/images/mac/checkbox.png
new file mode 100644
index 0000000000..4064909712
--- /dev/null
+++ b/examples/widgets/richtext/textedit/images/mac/checkbox.png
Binary files differ
diff --git a/examples/widgets/richtext/textedit/images/mac/format-indent-less.png b/examples/widgets/richtext/textedit/images/mac/format-indent-less.png
new file mode 100644
index 0000000000..e38074e78b
--- /dev/null
+++ b/examples/widgets/richtext/textedit/images/mac/format-indent-less.png
Binary files differ
diff --git a/examples/widgets/richtext/textedit/images/mac/format-indent-more.png b/examples/widgets/richtext/textedit/images/mac/format-indent-more.png
new file mode 100644
index 0000000000..1bdeabd354
--- /dev/null
+++ b/examples/widgets/richtext/textedit/images/mac/format-indent-more.png
Binary files differ
diff --git a/examples/widgets/richtext/textedit/images/win/checkbox-checked.png b/examples/widgets/richtext/textedit/images/win/checkbox-checked.png
new file mode 100644
index 0000000000..a072d7fb5c
--- /dev/null
+++ b/examples/widgets/richtext/textedit/images/win/checkbox-checked.png
Binary files differ
diff --git a/examples/widgets/richtext/textedit/images/win/checkbox.png b/examples/widgets/richtext/textedit/images/win/checkbox.png
new file mode 100644
index 0000000000..4064909712
--- /dev/null
+++ b/examples/widgets/richtext/textedit/images/win/checkbox.png
Binary files differ
diff --git a/examples/widgets/richtext/textedit/images/win/format-indent-less.png b/examples/widgets/richtext/textedit/images/win/format-indent-less.png
new file mode 100644
index 0000000000..e38074e78b
--- /dev/null
+++ b/examples/widgets/richtext/textedit/images/win/format-indent-less.png
Binary files differ
diff --git a/examples/widgets/richtext/textedit/images/win/format-indent-more.png b/examples/widgets/richtext/textedit/images/win/format-indent-more.png
new file mode 100644
index 0000000000..1bdeabd354
--- /dev/null
+++ b/examples/widgets/richtext/textedit/images/win/format-indent-more.png
Binary files differ
diff --git a/examples/widgets/richtext/textedit/textedit.cpp b/examples/widgets/richtext/textedit/textedit.cpp
index 00ea0325dc..996bb8e0a4 100644
--- a/examples/widgets/richtext/textedit/textedit.cpp
+++ b/examples/widgets/richtext/textedit/textedit.cpp
@@ -71,6 +71,7 @@
#include <QCloseEvent>
#include <QMessageBox>
#include <QMimeData>
+#include <QMimeDatabase>
#if defined(QT_PRINTSUPPORT_LIB)
#include <QtPrintSupport/qtprintsupportglobal.h>
#if QT_CONFIG(printer)
@@ -316,6 +317,14 @@ void TextEdit::setupTextActions()
actionAlignJustify->setShortcut(Qt::CTRL + Qt::Key_J);
actionAlignJustify->setCheckable(true);
actionAlignJustify->setPriority(QAction::LowPriority);
+ const QIcon indentMoreIcon = QIcon::fromTheme("format-indent-more", QIcon(rsrcPath + "/format-indent-more.png"));
+ actionIndentMore = menu->addAction(indentMoreIcon, tr("&Indent"), this, &TextEdit::indent);
+ actionIndentMore->setShortcut(Qt::CTRL + Qt::Key_BracketRight);
+ actionIndentMore->setPriority(QAction::LowPriority);
+ const QIcon indentLessIcon = QIcon::fromTheme("format-indent-less", QIcon(rsrcPath + "/format-indent-less.png"));
+ actionIndentLess = menu->addAction(indentLessIcon, tr("&Unindent"), this, &TextEdit::unindent);
+ actionIndentLess->setShortcut(Qt::CTRL + Qt::Key_BracketLeft);
+ actionIndentLess->setPriority(QAction::LowPriority);
// Make sure the alignLeft is always left of the alignRight
QActionGroup *alignGroup = new QActionGroup(this);
@@ -334,6 +343,10 @@ void TextEdit::setupTextActions()
tb->addActions(alignGroup->actions());
menu->addActions(alignGroup->actions());
+ tb->addAction(actionIndentMore);
+ tb->addAction(actionIndentLess);
+ menu->addAction(actionIndentMore);
+ menu->addAction(actionIndentLess);
menu->addSeparator();
@@ -342,6 +355,15 @@ void TextEdit::setupTextActions()
actionTextColor = menu->addAction(pix, tr("&Color..."), this, &TextEdit::textColor);
tb->addAction(actionTextColor);
+ menu->addSeparator();
+
+ const QIcon checkboxIcon = QIcon::fromTheme("status-checkbox-checked", QIcon(rsrcPath + "/checkbox-checked.png"));
+ actionToggleCheckState = menu->addAction(checkboxIcon, tr("Chec&ked"), this, &TextEdit::setChecked);
+ actionToggleCheckState->setShortcut(Qt::CTRL + Qt::Key_K);
+ actionToggleCheckState->setCheckable(true);
+ actionToggleCheckState->setPriority(QAction::LowPriority);
+ tb->addAction(actionToggleCheckState);
+
tb = addToolBar(tr("Format Actions"));
tb->setAllowedAreas(Qt::TopToolBarArea | Qt::BottomToolBarArea);
addToolBarBreak(Qt::TopToolBarArea);
@@ -353,6 +375,8 @@ void TextEdit::setupTextActions()
comboStyle->addItem("Bullet List (Disc)");
comboStyle->addItem("Bullet List (Circle)");
comboStyle->addItem("Bullet List (Square)");
+ comboStyle->addItem("Task List (Unchecked)");
+ comboStyle->addItem("Task List (Checked)");
comboStyle->addItem("Ordered List (Decimal)");
comboStyle->addItem("Ordered List (Alpha lower)");
comboStyle->addItem("Ordered List (Alpha upper)");
@@ -369,7 +393,7 @@ void TextEdit::setupTextActions()
comboFont = new QFontComboBox(tb);
tb->addWidget(comboFont);
- connect(comboFont, QOverload<const QString &>::of(&QComboBox::activated), this, &TextEdit::textFamily);
+ connect(comboFont, &QComboBox::textActivated, this, &TextEdit::textFamily);
comboSize = new QComboBox(tb);
comboSize->setObjectName("comboSize");
@@ -381,7 +405,7 @@ void TextEdit::setupTextActions()
comboSize->addItem(QString::number(size));
comboSize->setCurrentIndex(standardSizes.indexOf(QApplication::font().pointSize()));
- connect(comboSize, QOverload<const QString &>::of(&QComboBox::activated), this, &TextEdit::textSize);
+ connect(comboSize, &QComboBox::textActivated, this, &TextEdit::textSize);
}
bool TextEdit::load(const QString &f)
@@ -395,11 +419,18 @@ bool TextEdit::load(const QString &f)
QByteArray data = file.readAll();
QTextCodec *codec = Qt::codecForHtml(data);
QString str = codec->toUnicode(data);
+ QUrl baseUrl = (f.front() == QLatin1Char(':') ? QUrl(f) : QUrl::fromLocalFile(f)).adjusted(QUrl::RemoveFilename);
+ textEdit->document()->setBaseUrl(baseUrl);
if (Qt::mightBeRichText(str)) {
textEdit->setHtml(str);
} else {
- str = QString::fromLocal8Bit(data);
- textEdit->setPlainText(str);
+#if QT_CONFIG(textmarkdownreader)
+ QMimeDatabase db;
+ if (db.mimeTypeForFileNameAndData(f, data).name() == QLatin1String("text/markdown"))
+ textEdit->setMarkdown(str);
+ else
+#endif
+ textEdit->setPlainText(QString::fromLocal8Bit(data));
}
setCurrentFileName(f);
@@ -451,7 +482,15 @@ void TextEdit::fileOpen()
QFileDialog fileDialog(this, tr("Open File..."));
fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
fileDialog.setFileMode(QFileDialog::ExistingFile);
- fileDialog.setMimeTypeFilters(QStringList() << "text/html" << "text/plain");
+ fileDialog.setMimeTypeFilters(QStringList()
+#if QT_CONFIG(texthtmlparser)
+ << "text/html"
+#endif
+#if QT_CONFIG(textmarkdownreader)
+
+ << "text/markdown"
+#endif
+ << "text/plain");
if (fileDialog.exec() != QDialog::Accepted)
return;
const QString fn = fileDialog.selectedFiles().first();
@@ -485,9 +524,18 @@ bool TextEdit::fileSaveAs()
QFileDialog fileDialog(this, tr("Save as..."));
fileDialog.setAcceptMode(QFileDialog::AcceptSave);
QStringList mimeTypes;
- mimeTypes << "application/vnd.oasis.opendocument.text" << "text/html" << "text/plain";
+ mimeTypes << "text/plain"
+#if QT_CONFIG(textodfwriter)
+ << "application/vnd.oasis.opendocument.text"
+#endif
+#if QT_CONFIG(textmarkdownwriter)
+ << "text/markdown"
+#endif
+ << "text/html";
fileDialog.setMimeTypeFilters(mimeTypes);
+#if QT_CONFIG(textodfwriter)
fileDialog.setDefaultSuffix("odt");
+#endif
if (fileDialog.exec() != QDialog::Accepted)
return false;
const QString fn = fileDialog.selectedFiles().first();
@@ -592,6 +640,7 @@ void TextEdit::textStyle(int styleIndex)
{
QTextCursor cursor = textEdit->textCursor();
QTextListFormat::Style style = QTextListFormat::ListStyleUndefined;
+ QTextBlockFormat::MarkerType marker = QTextBlockFormat::NoMarker;
switch (styleIndex) {
case 1:
@@ -604,18 +653,32 @@ void TextEdit::textStyle(int styleIndex)
style = QTextListFormat::ListSquare;
break;
case 4:
- style = QTextListFormat::ListDecimal;
+ if (cursor.currentList())
+ style = cursor.currentList()->format().style();
+ else
+ style = QTextListFormat::ListDisc;
+ marker = QTextBlockFormat::Unchecked;
break;
case 5:
- style = QTextListFormat::ListLowerAlpha;
+ if (cursor.currentList())
+ style = cursor.currentList()->format().style();
+ else
+ style = QTextListFormat::ListDisc;
+ marker = QTextBlockFormat::Checked;
break;
case 6:
- style = QTextListFormat::ListUpperAlpha;
+ style = QTextListFormat::ListDecimal;
break;
case 7:
- style = QTextListFormat::ListLowerRoman;
+ style = QTextListFormat::ListLowerAlpha;
break;
case 8:
+ style = QTextListFormat::ListUpperAlpha;
+ break;
+ case 9:
+ style = QTextListFormat::ListLowerRoman;
+ break;
+ case 10:
style = QTextListFormat::ListUpperRoman;
break;
default:
@@ -628,7 +691,7 @@ void TextEdit::textStyle(int styleIndex)
if (style == QTextListFormat::ListStyleUndefined) {
blockFmt.setObjectIndex(-1);
- int headingLevel = styleIndex >= 9 ? styleIndex - 9 + 1 : 0; // H1 to H6, or Standard
+ int headingLevel = styleIndex >= 11 ? styleIndex - 11 + 1 : 0; // H1 to H6, or Standard
blockFmt.setHeadingLevel(headingLevel);
cursor.setBlockFormat(blockFmt);
@@ -640,6 +703,8 @@ void TextEdit::textStyle(int styleIndex)
cursor.mergeCharFormat(fmt);
textEdit->mergeCurrentCharFormat(fmt);
} else {
+ blockFmt.setMarker(marker);
+ cursor.setBlockFormat(blockFmt);
QTextListFormat listFmt;
if (cursor.currentList()) {
listFmt = cursor.currentList()->format();
@@ -678,6 +743,45 @@ void TextEdit::textAlign(QAction *a)
textEdit->setAlignment(Qt::AlignJustify);
}
+void TextEdit::setChecked(bool checked)
+{
+ textStyle(checked ? 5 : 4);
+}
+
+void TextEdit::indent()
+{
+ modifyIndentation(1);
+}
+
+void TextEdit::unindent()
+{
+ modifyIndentation(-1);
+}
+
+void TextEdit::modifyIndentation(int amount)
+{
+ QTextCursor cursor = textEdit->textCursor();
+ cursor.beginEditBlock();
+ if (cursor.currentList()) {
+ QTextListFormat listFmt = cursor.currentList()->format();
+ // See whether the line above is the list we want to move this item into,
+ // or whether we need a new list.
+ QTextCursor above(cursor);
+ above.movePosition(QTextCursor::Up);
+ if (above.currentList() && listFmt.indent() + amount == above.currentList()->format().indent()) {
+ above.currentList()->add(cursor.block());
+ } else {
+ listFmt.setIndent(listFmt.indent() + amount);
+ cursor.createList(listFmt);
+ }
+ } else {
+ QTextBlockFormat blockFmt = cursor.blockFormat();
+ blockFmt.setIndent(blockFmt.indent() + amount);
+ cursor.setBlockFormat(blockFmt);
+ }
+ cursor.endEditBlock();
+}
+
void TextEdit::currentCharFormatChanged(const QTextCharFormat &format)
{
fontChanged(format.font());
@@ -700,27 +804,40 @@ void TextEdit::cursorPositionChanged()
comboStyle->setCurrentIndex(3);
break;
case QTextListFormat::ListDecimal:
- comboStyle->setCurrentIndex(4);
+ comboStyle->setCurrentIndex(6);
break;
case QTextListFormat::ListLowerAlpha:
- comboStyle->setCurrentIndex(5);
+ comboStyle->setCurrentIndex(7);
break;
case QTextListFormat::ListUpperAlpha:
- comboStyle->setCurrentIndex(6);
+ comboStyle->setCurrentIndex(8);
break;
case QTextListFormat::ListLowerRoman:
- comboStyle->setCurrentIndex(7);
+ comboStyle->setCurrentIndex(9);
break;
case QTextListFormat::ListUpperRoman:
- comboStyle->setCurrentIndex(8);
+ comboStyle->setCurrentIndex(10);
break;
default:
comboStyle->setCurrentIndex(-1);
break;
}
+ switch (textEdit->textCursor().block().blockFormat().marker()) {
+ case QTextBlockFormat::NoMarker:
+ actionToggleCheckState->setChecked(false);
+ break;
+ case QTextBlockFormat::Unchecked:
+ comboStyle->setCurrentIndex(4);
+ actionToggleCheckState->setChecked(false);
+ break;
+ case QTextBlockFormat::Checked:
+ comboStyle->setCurrentIndex(5);
+ actionToggleCheckState->setChecked(true);
+ break;
+ }
} else {
int headingLevel = textEdit->textCursor().blockFormat().headingLevel();
- comboStyle->setCurrentIndex(headingLevel ? headingLevel + 8 : 0);
+ comboStyle->setCurrentIndex(headingLevel ? headingLevel + 10 : 0);
}
}
diff --git a/examples/widgets/richtext/textedit/textedit.h b/examples/widgets/richtext/textedit/textedit.h
index ae0b13a4cc..9e50166c6f 100644
--- a/examples/widgets/richtext/textedit/textedit.h
+++ b/examples/widgets/richtext/textedit/textedit.h
@@ -96,6 +96,9 @@ private slots:
void textStyle(int styleIndex);
void textColor();
void textAlign(QAction *a);
+ void setChecked(bool checked);
+ void indent();
+ void unindent();
void currentCharFormatChanged(const QTextCharFormat &format);
void cursorPositionChanged();
@@ -110,6 +113,7 @@ private:
void setupTextActions();
bool maybeSave();
void setCurrentFileName(const QString &fileName);
+ void modifyIndentation(int amount);
void mergeFormatOnWordOrSelection(const QTextCharFormat &format);
void fontChanged(const QFont &f);
@@ -125,6 +129,9 @@ private:
QAction *actionAlignCenter;
QAction *actionAlignRight;
QAction *actionAlignJustify;
+ QAction *actionIndentLess;
+ QAction *actionIndentMore;
+ QAction *actionToggleCheckState;
QAction *actionUndo;
QAction *actionRedo;
#ifndef QT_NO_CLIPBOARD
diff --git a/examples/widgets/richtext/textedit/textedit.qrc b/examples/widgets/richtext/textedit/textedit.qrc
index 7d6efd7d67..1641acc207 100644
--- a/examples/widgets/richtext/textedit/textedit.qrc
+++ b/examples/widgets/richtext/textedit/textedit.qrc
@@ -1,6 +1,8 @@
<!DOCTYPE RCC><RCC version="1.0">
<qresource prefix="/">
<file>images/logo32.png</file>
+ <file>images/mac/checkbox.png</file>
+ <file>images/mac/checkbox-checked.png</file>
<file>images/mac/editcopy.png</file>
<file>images/mac/editcut.png</file>
<file>images/mac/editpaste.png</file>
@@ -11,6 +13,8 @@
<file>images/mac/fileopen.png</file>
<file>images/mac/fileprint.png</file>
<file>images/mac/filesave.png</file>
+ <file>images/mac/format-indent-less.png</file>
+ <file>images/mac/format-indent-more.png</file>
<file>images/mac/textbold.png</file>
<file>images/mac/textcenter.png</file>
<file>images/mac/textitalic.png</file>
@@ -20,6 +24,8 @@
<file>images/mac/textunder.png</file>
<file>images/mac/zoomin.png</file>
<file>images/mac/zoomout.png</file>
+ <file>images/win/checkbox.png</file>
+ <file>images/win/checkbox-checked.png</file>
<file>images/win/editcopy.png</file>
<file>images/win/editcut.png</file>
<file>images/win/editpaste.png</file>
@@ -30,6 +36,8 @@
<file>images/win/fileopen.png</file>
<file>images/win/fileprint.png</file>
<file>images/win/filesave.png</file>
+ <file>images/win/format-indent-less.png</file>
+ <file>images/win/format-indent-more.png</file>
<file>images/win/textbold.png</file>
<file>images/win/textcenter.png</file>
<file>images/win/textitalic.png</file>
diff --git a/examples/widgets/statemachine/factorial/main.cpp b/examples/widgets/statemachine/factorial/main.cpp
index 2d25822828..e9431596fe 100644
--- a/examples/widgets/statemachine/factorial/main.cpp
+++ b/examples/widgets/statemachine/factorial/main.cpp
@@ -49,7 +49,6 @@
****************************************************************************/
#include <QtCore>
-#include <stdio.h>
//! [0]
class Factorial : public QObject
@@ -143,7 +142,7 @@ public:
void onTransition(QEvent *) override
{
- fprintf(stdout, "%d\n", m_fact->property("fac").toInt());
+ qInfo() << m_fact->property("fac").toInt();
}
private:
diff --git a/examples/widgets/tools/i18n/languagechooser.cpp b/examples/widgets/tools/i18n/languagechooser.cpp
index f07d0ddee3..963165ff81 100644
--- a/examples/widgets/tools/i18n/languagechooser.cpp
+++ b/examples/widgets/tools/i18n/languagechooser.cpp
@@ -163,11 +163,8 @@ QStringList LanguageChooser::findQmFiles()
QDir dir(":/translations");
QStringList fileNames = dir.entryList(QStringList("*.qm"), QDir::Files,
QDir::Name);
- QMutableStringListIterator i(fileNames);
- while (i.hasNext()) {
- i.next();
- i.setValue(dir.filePath(i.value()));
- }
+ for (QString &fileName : fileNames)
+ fileName = dir.filePath(fileName);
return fileNames;
}
diff --git a/examples/widgets/tools/plugandpaint/app/interfaces.h b/examples/widgets/tools/plugandpaint/app/interfaces.h
index a1e91e13ff..705e578809 100644
--- a/examples/widgets/tools/plugandpaint/app/interfaces.h
+++ b/examples/widgets/tools/plugandpaint/app/interfaces.h
@@ -68,7 +68,7 @@ QT_END_NAMESPACE
class BrushInterface
{
public:
- virtual ~BrushInterface() {}
+ virtual ~BrushInterface() = default;
virtual QStringList brushes() const = 0;
virtual QRect mousePress(const QString &brush, QPainter &painter,
@@ -84,7 +84,7 @@ public:
class ShapeInterface
{
public:
- virtual ~ShapeInterface() {}
+ virtual ~ShapeInterface() = default;
virtual QStringList shapes() const = 0;
virtual QPainterPath generateShape(const QString &shape,
@@ -96,7 +96,7 @@ public:
class FilterInterface
{
public:
- virtual ~FilterInterface() {}
+ virtual ~FilterInterface() = default;
virtual QStringList filters() const = 0;
virtual QImage filterImage(const QString &filter, const QImage &image,
diff --git a/examples/widgets/tools/plugandpaint/app/paintarea.cpp b/examples/widgets/tools/plugandpaint/app/paintarea.cpp
index 4295e04cc0..e225d78398 100644
--- a/examples/widgets/tools/plugandpaint/app/paintarea.cpp
+++ b/examples/widgets/tools/plugandpaint/app/paintarea.cpp
@@ -59,7 +59,7 @@ PaintArea::PaintArea(QWidget *parent) :
QWidget(parent)
{
setAttribute(Qt::WA_StaticContents);
- setAttribute(Qt::WA_NoBackground);
+ setAttribute(Qt::WA_OpaquePaintEvent);
theImage.fill(qRgb(255, 255, 255));
}
diff --git a/examples/widgets/widgets/charactermap/mainwindow.cpp b/examples/widgets/widgets/charactermap/mainwindow.cpp
index e84ded5afb..77aad145e7 100644
--- a/examples/widgets/widgets/charactermap/mainwindow.cpp
+++ b/examples/widgets/widgets/charactermap/mainwindow.cpp
@@ -114,9 +114,9 @@ MainWindow::MainWindow(QWidget *parent)
this, &MainWindow::findSizes);
connect(fontCombo, &QFontComboBox::currentFontChanged,
characterWidget, &CharacterWidget::updateFont);
- connect(sizeCombo, QOverload<const QString &>::of(&QComboBox::currentIndexChanged),
+ connect(sizeCombo, &QComboBox::currentTextChanged,
characterWidget, &CharacterWidget::updateSize);
- connect(styleCombo, QOverload<const QString &>::of(&QComboBox::currentIndexChanged),
+ connect(styleCombo, &QComboBox::currentTextChanged,
characterWidget, &CharacterWidget::updateStyle);
//! [4] //! [5]
connect(characterWidget, &CharacterWidget::characterSelected,
diff --git a/examples/widgets/widgets/icons/iconpreviewarea.cpp b/examples/widgets/widgets/icons/iconpreviewarea.cpp
index 1a2f514ba8..7a73a137cd 100644
--- a/examples/widgets/widgets/icons/iconpreviewarea.cpp
+++ b/examples/widgets/widgets/icons/iconpreviewarea.cpp
@@ -79,8 +79,6 @@ IconPreviewArea::IconPreviewArea(QWidget *parent)
}
//! [0]
-#ifdef Q_COMPILER_INITIALIZER_LISTS
-
//! [42]
QVector<QIcon::Mode> IconPreviewArea::iconModes()
{
@@ -107,44 +105,6 @@ QStringList IconPreviewArea::iconStateNames()
}
//! [42]
-#else // Q_COMPILER_INITIALIZER_LISTS
-
-//! [43]
-QVector<QIcon::Mode> IconPreviewArea::iconModes()
-{
- static QVector<QIcon::Mode> result;
- if (result.isEmpty())
- result << QIcon::Normal << QIcon::Active << QIcon::Disabled << QIcon::Selected;
- return result;
-}
-//! [43]
-
-QVector<QIcon::State> IconPreviewArea::iconStates()
-{
- static QVector<QIcon::State> result;
- if (result.isEmpty())
- result << QIcon::Off << QIcon::On;
- return result;
-}
-
-QStringList IconPreviewArea::iconModeNames()
-{
- static QStringList result;
- if (result.isEmpty())
- result << tr("Normal") << tr("Active") << tr("Disabled") << tr("Selected");
- return result;
-}
-
-QStringList IconPreviewArea::iconStateNames()
-{
- static QStringList result;
- if (result.isEmpty())
- result << tr("Off") << tr("On");
- return result;
-}
-
-#endif // !Q_COMPILER_INITIALIZER_LISTS
-
//! [1]
void IconPreviewArea::setIcon(const QIcon &icon)
{
diff --git a/examples/widgets/widgets/icons/mainwindow.cpp b/examples/widgets/widgets/icons/mainwindow.cpp
index 0cf11c978d..91e98ff896 100644
--- a/examples/widgets/widgets/icons/mainwindow.cpp
+++ b/examples/widgets/widgets/icons/mainwindow.cpp
@@ -55,6 +55,8 @@
#include "imagedelegate.h"
#include "mainwindow.h"
+#include <memory>
+
//! [40]
enum { OtherSize = QStyle::PM_CustomBase };
//! [40]
@@ -514,8 +516,8 @@ void MainWindow::checkCurrentStyle()
const QList<QAction *> actions = styleActionGroup->actions();
for (QAction *action : actions) {
const QString styleName = action->data().toString();
- QScopedPointer<QStyle> candidate(QStyleFactory::create(styleName));
- Q_ASSERT(!candidate.isNull());
+ const std::unique_ptr<QStyle> candidate{QStyleFactory::create(styleName)};
+ Q_ASSERT(candidate);
if (candidate->metaObject()->className()
== QApplication::style()->metaObject()->className()) {
action->trigger();
diff --git a/examples/widgets/widgets/imageviewer/imageviewer.cpp b/examples/widgets/widgets/imageviewer/imageviewer.cpp
index fed551dade..2fc8ff63de 100644
--- a/examples/widgets/widgets/imageviewer/imageviewer.cpp
+++ b/examples/widgets/widgets/imageviewer/imageviewer.cpp
@@ -106,6 +106,8 @@ bool ImageViewer::loadFile(const QString &fileName)
void ImageViewer::setImage(const QImage &newImage)
{
image = newImage;
+ if (image.colorSpace().isValid())
+ image.convertToColorSpace(QColorSpace::SRgb);
imageLabel->setPixmap(QPixmap::fromImage(image));
//! [4]
scaleFactor = 1.0;
diff --git a/examples/widgets/widgets/spinboxes/window.cpp b/examples/widgets/widgets/spinboxes/window.cpp
index fd7c5b527e..82e19527a7 100644
--- a/examples/widgets/widgets/spinboxes/window.cpp
+++ b/examples/widgets/widgets/spinboxes/window.cpp
@@ -176,7 +176,7 @@ void Window::createDateTimeEdits()
formatComboBox->addItem("hh:mm ap");
//! [9] //! [10]
- connect(formatComboBox, QOverload<const QString &>::of(&QComboBox::activated),
+ connect(formatComboBox, &QComboBox::textActivated,
this, &Window::setFormatString);
//! [10]
diff --git a/examples/widgets/widgets/styles/widgetgallery.cpp b/examples/widgets/widgets/styles/widgetgallery.cpp
index f0a0336a94..34c010df74 100644
--- a/examples/widgets/widgets/styles/widgetgallery.cpp
+++ b/examples/widgets/widgets/styles/widgetgallery.cpp
@@ -79,7 +79,7 @@ WidgetGallery::WidgetGallery(QWidget *parent)
//! [0]
//! [1]
- connect(styleComboBox, QOverload<const QString &>::of(&QComboBox::activated),
+ connect(styleComboBox, &QComboBox::textActivated,
//! [1] //! [2]
this, &WidgetGallery::changeStyle);
connect(useStylePaletteCheckBox, &QCheckBox::toggled,
diff --git a/examples/xml/htmlinfo/main.cpp b/examples/xml/htmlinfo/main.cpp
index 22bf36f33c..bc19ae4a82 100644
--- a/examples/xml/htmlinfo/main.cpp
+++ b/examples/xml/htmlinfo/main.cpp
@@ -54,10 +54,10 @@ void parseHtmlFile(QTextStream &out, const QString &fileName)
{
QFile file(fileName);
- out << "Analysis of HTML file: " << fileName << endl;
+ out << "Analysis of HTML file: " << fileName << Qt::endl;
if (!file.open(QIODevice::ReadOnly)) {
- out << " Couldn't open the file." << endl << endl << endl;
+ out << " Couldn't open the file." << Qt::endl << Qt::endl << Qt::endl;
return;
}
@@ -85,22 +85,22 @@ void parseHtmlFile(QTextStream &out, const QString &fileName)
//! [2]
if (reader.hasError()) {
out << " The HTML file isn't well-formed: " << reader.errorString()
- << endl << endl << endl;
+ << Qt::endl << Qt::endl << Qt::endl;
return;
}
//! [2]
- out << " Title: \"" << title << '"' << endl
- << " Number of paragraphs: " << paragraphCount << endl
- << " Number of links: " << links.size() << endl
- << " Showing first few links:" << endl;
+ out << " Title: \"" << title << '"' << Qt::endl
+ << " Number of paragraphs: " << paragraphCount << Qt::endl
+ << " Number of links: " << links.size() << Qt::endl
+ << " Showing first few links:" << Qt::endl;
while (links.size() > 5)
links.removeLast();
for (const QString &link : qAsConst(links))
- out << " " << link << endl;
- out << endl << endl;
+ out << " " << link << Qt::endl;
+ out << Qt::endl << Qt::endl;
}
int main(int argc, char **argv)