diff options
author | Liang Qi <liang.qi@theqtcompany.com> | 2015-10-14 15:45:35 +0200 |
---|---|---|
committer | Liang Qi <liang.qi@theqtcompany.com> | 2015-10-14 15:45:35 +0200 |
commit | 4456984da780b14572e1ec0f079a4d349ab299bd (patch) | |
tree | f586a281a81c57c91c49e83a5d3ec6c7eece0578 /examples | |
parent | e824abd987d77efaa085fe1f9fb514d270798d55 (diff) | |
parent | 281121697340084f7d385eab530f41916789b94d (diff) |
Merge remote-tracking branch 'origin/5.6' into dev
Conflicts:
tests/auto/corelib/io/qfile/tst_qfile.cpp
tests/auto/corelib/io/qprocess/tst_qprocess.cpp
tests/auto/corelib/tools/qversionnumber/qversionnumber.pro
Change-Id: Ia93ce500349d96a2fbf0b4a37b73f088cc505c6e
Diffstat (limited to 'examples')
50 files changed, 345 insertions, 333 deletions
diff --git a/examples/embedded/digiflip/digiflip.cpp b/examples/embedded/digiflip/digiflip.cpp index 3bb3023caf..af4289efb3 100644 --- a/examples/embedded/digiflip/digiflip.cpp +++ b/examples/embedded/digiflip/digiflip.cpp @@ -112,7 +112,7 @@ protected: QString str = QString::number(n); if (str.length() == 1) - str.prepend("0"); + str.prepend('0'); QFont font; font.setFamily("Helvetica"); diff --git a/examples/gui/openglwindow/main.cpp b/examples/gui/openglwindow/main.cpp index 6ab05176a6..d79ecd6510 100644 --- a/examples/gui/openglwindow/main.cpp +++ b/examples/gui/openglwindow/main.cpp @@ -57,8 +57,6 @@ public: void render() Q_DECL_OVERRIDE; private: - GLuint loadShader(GLenum type, const char *source); - GLuint m_posAttr; GLuint m_colAttr; GLuint m_matrixUniform; @@ -113,14 +111,6 @@ static const char *fragmentShaderSource = //! [3] //! [4] -GLuint TriangleWindow::loadShader(GLenum type, const char *source) -{ - GLuint shader = glCreateShader(type); - glShaderSource(shader, 1, &source, 0); - glCompileShader(shader); - return shader; -} - void TriangleWindow::initialize() { m_program = new QOpenGLShaderProgram(this); diff --git a/examples/network/doc/src/torrent.qdoc b/examples/network/doc/src/torrent.qdoc index 08857f02d3..9576e08cfa 100644 --- a/examples/network/doc/src/torrent.qdoc +++ b/examples/network/doc/src/torrent.qdoc @@ -35,37 +35,4 @@ supported by the Qt Network APIs. \image torrent-example.png - - \section1 License Information - - The implementation of the US Secure Hash Algorithm 1 (SHA1) in this example is - derived from the original description in \l{http://www.rfc-editor.org/rfc/rfc3174.txt}{RFC 3174}. - - \legalese - Copyright (C) The Internet Society (2001). All Rights Reserved. - - This document and translations of it may be copied and furnished to - others, and derivative works that comment on or otherwise explain it - or assist in its implementation may be prepared, copied, published - and distributed, in whole or in part, without restriction of any - kind, provided that the above copyright notice and this paragraph are - included on all such copies and derivative works. However, this - document itself may not be modified in any way, such as by removing - the copyright notice or references to the Internet Society or other - Internet organizations, except as needed for the purpose of - developing Internet standards in which case the procedures for - copyrights defined in the Internet Standards process must be - followed, or as required to translate it into languages other than - English. - - The limited permissions granted above are perpetual and will not be - revoked by the Internet Society or its successors or assigns. - - This document and the information contained herein is provided on an - "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING - TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING - BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION - HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF - MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. - \endlegalese */ diff --git a/examples/network/torrent/filemanager.cpp b/examples/network/torrent/filemanager.cpp index b4e921b0a5..58330014cf 100644 --- a/examples/network/torrent/filemanager.cpp +++ b/examples/network/torrent/filemanager.cpp @@ -219,8 +219,8 @@ bool FileManager::generateFiles() QString prefix; if (!destinationPath.isEmpty()) { prefix = destinationPath; - if (!prefix.endsWith("/")) - prefix += "/"; + if (!prefix.endsWith('/')) + prefix += '/'; QDir dir; if (!dir.mkpath(prefix)) { errString = tr("Failed to create directory %1").arg(prefix); @@ -261,13 +261,13 @@ bool FileManager::generateFiles() if (!destinationPath.isEmpty()) { prefix = destinationPath; - if (!prefix.endsWith("/")) - prefix += "/"; + if (!prefix.endsWith('/')) + prefix += '/'; } if (!metaInfo.name().isEmpty()) { prefix += metaInfo.name(); - if (!prefix.endsWith("/")) - prefix += "/"; + if (!prefix.endsWith('/')) + prefix += '/'; } if (!dir.mkpath(prefix)) { errString = tr("Failed to create directory %1").arg(prefix); diff --git a/examples/network/torrent/metainfo.cpp b/examples/network/torrent/metainfo.cpp index cca52c7e7e..52e7afe43a 100644 --- a/examples/network/torrent/metainfo.cpp +++ b/examples/network/torrent/metainfo.cpp @@ -96,7 +96,7 @@ bool MetaInfo::parse(const QByteArray &data) QByteArray path; foreach (QVariant p, pathElements) { if (!path.isEmpty()) - path += "/"; + path += '/'; path += p.toByteArray(); } diff --git a/examples/opengl/contextinfo/widget.cpp b/examples/opengl/contextinfo/widget.cpp index c318accf87..2d36fe4265 100644 --- a/examples/opengl/contextinfo/widget.cpp +++ b/examples/opengl/contextinfo/widget.cpp @@ -299,7 +299,7 @@ void Widget::printFormat(const QSurfaceFormat &format) QString opts; for (size_t i = 0; i < sizeof(options) / sizeof(Option); ++i) if (format.testOption(options[i].option)) - opts += QString::fromLatin1(options[i].str) + QStringLiteral(" "); + opts += QString::fromLatin1(options[i].str) + QLatin1Char(' '); m_output->append(tr("Options: %1").arg(opts)); for (size_t i = 0; i < sizeof(renderables) / sizeof(Renderable); ++i) diff --git a/examples/qtconcurrent/wordcount/main.cpp b/examples/qtconcurrent/wordcount/main.cpp index f45f2820c7..7f6d0f43ba 100644 --- a/examples/qtconcurrent/wordcount/main.cpp +++ b/examples/qtconcurrent/wordcount/main.cpp @@ -61,10 +61,10 @@ QStringList findFiles(const QString &startDir, QStringList filters) QDir dir(startDir); foreach (QString file, dir.entryList(filters, QDir::Files)) - names += startDir + "/" + file; + names += startDir + '/' + file; foreach (QString subdir, dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot)) - names += findFiles(startDir + "/" + subdir, filters); + names += findFiles(startDir + '/' + subdir, filters); return names; } @@ -81,7 +81,7 @@ WordCount singleThreadedWordCount(QStringList files) f.open(QIODevice::ReadOnly); QTextStream textStream(&f); while (textStream.atEnd() == false) - foreach(QString word, textStream.readLine().split(" ")) + foreach (const QString &word, textStream.readLine().split(' ')) wordCount[word] += 1; } @@ -100,7 +100,7 @@ WordCount countWords(const QString &file) WordCount wordCount; while (textStream.atEnd() == false) - foreach (QString word, textStream.readLine().split(" ")) + foreach (const QString &word, textStream.readLine().split(' ')) wordCount[word] += 1; return wordCount; diff --git a/examples/sql/masterdetail/dialog.cpp b/examples/sql/masterdetail/dialog.cpp index 5518707f58..3171acc448 100644 --- a/examples/sql/masterdetail/dialog.cpp +++ b/examples/sql/masterdetail/dialog.cpp @@ -153,7 +153,7 @@ void Dialog::addTracks(int albumId, QStringList tracks) for (int i = 0; i < tracks.count(); i++) { QString trackNumber = QString::number(i); if (i < 10) - trackNumber.prepend("0"); + trackNumber.prepend('0'); QDomText textNode = albumDetails.createTextNode(tracks.at(i)); diff --git a/examples/sql/querymodel/customsqlmodel.cpp b/examples/sql/querymodel/customsqlmodel.cpp index 5966802abe..4cdfdd6ae3 100644 --- a/examples/sql/querymodel/customsqlmodel.cpp +++ b/examples/sql/querymodel/customsqlmodel.cpp @@ -53,7 +53,7 @@ QVariant CustomSqlModel::data(const QModelIndex &index, int role) const QVariant value = QSqlQueryModel::data(index, role); if (value.isValid() && role == Qt::DisplayRole) { if (index.column() == 0) - return value.toString().prepend("#"); + return value.toString().prepend('#'); else if (index.column() == 2) return value.toString().toUpper(); } diff --git a/examples/widgets/desktop/systray/doc/images/systemtray-editor.png b/examples/widgets/desktop/systray/doc/images/systemtray-editor.png Binary files differnew file mode 100644 index 0000000000..fb15dea8cb --- /dev/null +++ b/examples/widgets/desktop/systray/doc/images/systemtray-editor.png diff --git a/examples/widgets/desktop/systray/doc/images/systemtray-example.png b/examples/widgets/desktop/systray/doc/images/systemtray-example.png Binary files differnew file mode 100644 index 0000000000..98b5c8133e --- /dev/null +++ b/examples/widgets/desktop/systray/doc/images/systemtray-example.png diff --git a/examples/widgets/desktop/systray/doc/src/systray.qdoc b/examples/widgets/desktop/systray/doc/src/systray.qdoc new file mode 100644 index 0000000000..074012b6a7 --- /dev/null +++ b/examples/widgets/desktop/systray/doc/src/systray.qdoc @@ -0,0 +1,183 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:FDL$ +** 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 http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Free Documentation License Usage +** Alternatively, this file may be used under the terms of the GNU Free +** Documentation License version 1.3 as published by the Free Software +** Foundation and appearing in the file included in the packaging of +** this file. Please review the following information to ensure +** the GNU Free Documentation License version 1.3 requirements +** will be met: http://www.gnu.org/copyleft/fdl.html. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example desktop/systray + \title System Tray Icon Example + + + The System Tray Icon example shows how to add an icon with a menu + and popup messages to a desktop environment's system tray. + + \image systemtray-example.png Screenshot of the System Tray Icon. + + Modern operating systems usually provide a special area on the + desktop, called the system tray or notification area, where + long-running applications can display icons and short messages. + + This example consists of one single class, \c Window, providing + the main application window (i.e., an editor for the system tray + icon) and the associated icon. + + \image systemtray-editor.png + + The editor allows the user to choose the preferred icon as well as + set the balloon message's type and duration. The user can also + edit the message's title and body. Finally, the editor provide a + checkbox controlling whether the icon is actually shown in the + system tray, or not. + + \section1 Window Class Definition + + The \c Window class inherits QWidget: + + \snippet desktop/systray/window.h 0 + + We implement several private slots to respond to user + interaction. The other private functions are only convenience + functions provided to simplify the constructor. + + The tray icon is an instance of the QSystemTrayIcon class. To + check whether a system tray is present on the user's desktop, call + the static QSystemTrayIcon::isSystemTrayAvailable() + function. Associated with the icon, we provide a menu containing + the typical \gui minimize, \gui maximize, \gui restore and \gui + quit actions. We reimplement the QWidget::setVisible() function to + update the tray icon's menu whenever the editor's appearance + changes, e.g., when maximizing or minimizing the main application + window. + + Finally, we reimplement QWidget's \l {QWidget::}{closeEvent()} + function to be able to inform the user (when closing the editor + window) that the program will keep running in the system tray + until the user chooses the \gui Quit entry in the icon's context + menu. + + \section1 Window Class Implementation + + When constructing the editor widget, we first create the various + editor elements before we create the actual system tray icon: + + \snippet desktop/systray/window.cpp 0 + + We ensure that the application responds to user input by + connecting most of the editor's input widgets (including the + system tray icon) to the application's private slots. But note the + visibility checkbox; its \l {QCheckBox::}{toggled()} signal is + connected to the \e {icon}'s \l {QSystemTrayIcon::}{setVisible()} + function instead. + + \snippet desktop/systray/window.cpp 3 + + The \c setIcon() slot is triggered whenever the current index in + the icon combobox changes, i.e., whenever the user chooses another + icon in the editor. Note that it is also called when the user + activates the tray icon with the left mouse button, triggering the + icon's \l {QSystemTrayIcon::}{activated()} signal. We will come + back to this signal shortly. + + The QSystemTrayIcon::setIcon() function sets the \l + {QSystemTrayIcon::}{icon} property that holds the actual system + tray icon. On Windows, the system tray icon size is 16x16; on X11, + the preferred size is 22x22. The icon will be scaled to the + appropriate size as necessary. + + Note that on X11, due to a limitation in the system tray + specification, mouse clicks on transparent areas in the icon are + propagated to the system tray. If this behavior is unacceptable, + we suggest using an icon with no transparency. + + \snippet desktop/systray/window.cpp 4 + + Whenever the user activates the system tray icon, it emits its \l + {QSystemTrayIcon::}{activated()} signal passing the triggering + reason as parameter. QSystemTrayIcon provides the \l + {QSystemTrayIcon::}{ActivationReason} enum to describe how the + icon was activated. + + In the constructor, we connected our icon's \l + {QSystemTrayIcon::}{activated()} signal to our custom \c + iconActivated() slot: If the user has clicked the icon using the + left mouse button, this function changes the icon image by + incrementing the icon combobox's current index, triggering the \c + setIcon() slot as mentioned above. If the user activates the icon + using the middle mouse button, it calls the custom \c + showMessage() slot: + + \snippet desktop/systray/window.cpp 5 + + When the \e showMessage() slot is triggered, we first retrieve the + message icon depending on the currently chosen message type. The + QSystemTrayIcon::MessageIcon enum describes the icon that is shown + when a balloon message is displayed. Then we call + QSystemTrayIcon's \l {QSystemTrayIcon::}{showMessage()} function + to show the message with the title, body, and icon for the time + specified in milliseconds. + + OS X users note: The Growl notification system must be + installed for QSystemTrayIcon::showMessage() to display messages. + + QSystemTrayIcon also has the corresponding, \l {QSystemTrayIcon::} + {messageClicked()} signal, which is emitted when the user clicks a + message displayed by \l {QSystemTrayIcon::}{showMessage()}. + + \snippet desktop/systray/window.cpp 6 + + In the constructor, we connected the \l + {QSystemTrayIcon::}{messageClicked()} signal to our custom \c + messageClicked() slot that simply displays a message using the + QMessageBox class. + + QMessageBox provides a modal dialog with a short message, an icon, + and buttons laid out depending on the current style. It supports + four severity levels: "Question", "Information", "Warning" and + "Critical". The easiest way to pop up a message box in Qt is to + call one of the associated static functions, e.g., + QMessageBox::information(). + + As we mentioned earlier, we reimplement a couple of QWidget's + virtual functions: + + \snippet desktop/systray/window.cpp 1 + + Our reimplementation of the QWidget::setVisible() function updates + the tray icon's menu whenever the editor's appearance changes, + e.g., when maximizing or minimizing the main application window, + before calling the base class implementation. + + \snippet desktop/systray/window.cpp 2 + + We have reimplemented the QWidget::closeEvent() event handler to + receive widget close events, showing the above message to the + users when they are closing the editor window. + + 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. +*/ diff --git a/examples/widgets/dialogs/classwizard/classwizard.cpp b/examples/widgets/dialogs/classwizard/classwizard.cpp index c913d7b592..d3e366efe6 100644 --- a/examples/widgets/dialogs/classwizard/classwizard.cpp +++ b/examples/widgets/dialogs/classwizard/classwizard.cpp @@ -79,31 +79,31 @@ void ClassWizard::accept() if (field("comment").toBool()) { block += "/*\n"; - block += " " + header.toLatin1() + "\n"; + block += " " + header.toLatin1() + '\n'; block += "*/\n"; - block += "\n"; + block += '\n'; } if (field("protect").toBool()) { - block += "#ifndef " + macroName + "\n"; - block += "#define " + macroName + "\n"; - block += "\n"; + block += "#ifndef " + macroName + '\n'; + block += "#define " + macroName + '\n'; + block += '\n'; } if (field("includeBase").toBool()) { - block += "#include " + baseInclude + "\n"; - block += "\n"; + block += "#include " + baseInclude + '\n'; + block += '\n'; } block += "class " + className; if (!baseClass.isEmpty()) block += " : public " + baseClass; - block += "\n"; + block += '\n'; block += "{\n"; /* qmake ignore Q_OBJECT */ if (field("qobjectMacro").toBool()) { block += " Q_OBJECT\n"; - block += "\n"; + block += '\n'; } block += "public:\n"; @@ -115,7 +115,7 @@ void ClassWizard::accept() block += " " + className + "();\n"; if (field("copyCtor").toBool()) { block += " " + className + "(const " + className + " &other);\n"; - block += "\n"; + block += '\n'; block += " " + className + " &operator=" + "(const " + className + " &other);\n"; } @@ -123,11 +123,11 @@ void ClassWizard::accept() block += "};\n"; if (field("protect").toBool()) { - block += "\n"; + block += '\n'; block += "#endif\n"; } - QFile headerFile(outputDir + "/" + header); + QFile headerFile(outputDir + '/' + header); if (!headerFile.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(0, QObject::tr("Simple Wizard"), QObject::tr("Cannot write file %1:\n%2") @@ -141,12 +141,12 @@ void ClassWizard::accept() if (field("comment").toBool()) { block += "/*\n"; - block += " " + implementation.toLatin1() + "\n"; + block += " " + implementation.toLatin1() + '\n'; block += "*/\n"; - block += "\n"; + block += '\n'; } block += "#include \"" + header.toLatin1() + "\"\n"; - block += "\n"; + block += '\n'; if (field("qobjectCtor").toBool()) { block += className + "::" + className + "(QObject *parent)\n"; @@ -171,7 +171,7 @@ void ClassWizard::accept() block += "{\n"; block += " *this = other;\n"; block += "}\n"; - block += "\n"; + block += '\n'; block += className + " &" + className + "::operator=(const " + className + " &other)\n"; block += "{\n"; @@ -183,7 +183,7 @@ void ClassWizard::accept() } } - QFile implementationFile(outputDir + "/" + implementation); + QFile implementationFile(outputDir + '/' + implementation); if (!implementationFile.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(0, QObject::tr("Simple Wizard"), QObject::tr("Cannot write file %1:\n%2") @@ -356,9 +356,9 @@ void CodeStylePage::initializePage() if (baseClass.isEmpty()) { baseIncludeLineEdit->clear(); } else if (QRegExp("Q[A-Z].*").exactMatch(baseClass)) { - baseIncludeLineEdit->setText("<" + baseClass + ">"); + baseIncludeLineEdit->setText('<' + baseClass + '>'); } else { - baseIncludeLineEdit->setText("\"" + baseClass.toLower() + ".h\""); + baseIncludeLineEdit->setText('"' + baseClass.toLower() + ".h\""); } } //! [16] diff --git a/examples/widgets/doc/src/codeeditor.qdoc b/examples/widgets/doc/src/codeeditor.qdoc index 645854a58c..6c9e5921b8 100644 --- a/examples/widgets/doc/src/codeeditor.qdoc +++ b/examples/widgets/doc/src/codeeditor.qdoc @@ -192,6 +192,6 @@ fetched with QTextBlock::userData(). Matching parentheses can be highlighted with an extra selection. The "Matching Parentheses with QSyntaxHighlighter" article in Qt Quarterly 31 implements - this. You find it here: \l{http://doc.qt.digia.com/qq/}. + this. You find it here: \l{http://doc.qt.io/archives/qq/}. */ diff --git a/examples/widgets/doc/src/syntaxhighlighter.qdoc b/examples/widgets/doc/src/syntaxhighlighter.qdoc index 2b283afe5e..7d33299c81 100644 --- a/examples/widgets/doc/src/syntaxhighlighter.qdoc +++ b/examples/widgets/doc/src/syntaxhighlighter.qdoc @@ -248,7 +248,7 @@ It is possible to implement parenthesis matching with QSyntaxHighlighter. The "Matching Parentheses with QSyntaxHighlighter" article in Qt Quarterly 31 - (\l{http://doc.qt.digia.com/qq/}) implements this. We also have + (\l{http://doc.qt.io/archives/qq/}) implements this. We also have the \l{Code Editor Example}, which shows how to implement line numbers and how to highlight the current line. diff --git a/examples/widgets/draganddrop/draggableicons/main.cpp b/examples/widgets/draganddrop/draggableicons/main.cpp index 165f71dbf7..44b4f848bf 100644 --- a/examples/widgets/draganddrop/draggableicons/main.cpp +++ b/examples/widgets/draganddrop/draggableicons/main.cpp @@ -50,11 +50,10 @@ int main(int argc, char *argv[]) QApplication app(argc, argv); QWidget mainWidget; - QHBoxLayout *horizontalLayout = new QHBoxLayout; + QHBoxLayout *horizontalLayout = new QHBoxLayout(&mainWidget); horizontalLayout->addWidget(new DragWidget); horizontalLayout->addWidget(new DragWidget); - mainWidget.setLayout(horizontalLayout); mainWidget.setWindowTitle(QObject::tr("Draggable Icons")); mainWidget.show(); diff --git a/examples/widgets/draganddrop/draggabletext/draggabletext.pro b/examples/widgets/draganddrop/draggabletext/draggabletext.pro index 2815be1613..1add2a270e 100644 --- a/examples/widgets/draganddrop/draggabletext/draggabletext.pro +++ b/examples/widgets/draganddrop/draggabletext/draggabletext.pro @@ -1,10 +1,8 @@ QT += widgets -HEADERS = draglabel.h \ - dragwidget.h +HEADERS = dragwidget.h RESOURCES = draggabletext.qrc -SOURCES = draglabel.cpp \ - dragwidget.cpp \ +SOURCES = dragwidget.cpp \ main.cpp # install diff --git a/examples/widgets/draganddrop/draggabletext/draglabel.cpp b/examples/widgets/draganddrop/draggabletext/draglabel.cpp deleted file mode 100644 index 4e741fb6c8..0000000000 --- a/examples/widgets/draganddrop/draggabletext/draglabel.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2015 The Qt Company Ltd. -** Contact: http://www.qt.io/licensing/ -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of 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 "draglabel.h" - -DragLabel::DragLabel(const QString &text, QWidget *parent) - : QLabel(text, parent) -{ - setAutoFillBackground(true); - setFrameShape(QFrame::Panel); - setFrameShadow(QFrame::Raised); -} diff --git a/examples/widgets/draganddrop/draggabletext/draglabel.h b/examples/widgets/draganddrop/draggabletext/draglabel.h deleted file mode 100644 index 8d2c31aa1d..0000000000 --- a/examples/widgets/draganddrop/draggabletext/draglabel.h +++ /dev/null @@ -1,58 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2015 The Qt Company Ltd. -** Contact: http://www.qt.io/licensing/ -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of 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 DRAGLABEL_H -#define DRAGLABEL_H - -#include <QLabel> - -QT_BEGIN_NAMESPACE -class QDragEnterEvent; -class QDragMoveEvent; -class QFrame; -QT_END_NAMESPACE - -class DragLabel : public QLabel -{ -public: - DragLabel(const QString &text, QWidget *parent); -}; - -#endif // DRAGLABEL_H diff --git a/examples/widgets/draganddrop/draggabletext/dragwidget.cpp b/examples/widgets/draganddrop/draggabletext/dragwidget.cpp index 3b8bca3277..36c4df2e43 100644 --- a/examples/widgets/draganddrop/draggabletext/dragwidget.cpp +++ b/examples/widgets/draganddrop/draggabletext/dragwidget.cpp @@ -40,13 +40,23 @@ #include <QtWidgets> -#include "draglabel.h" #include "dragwidget.h" +static QLabel *createDragLabel(const QString &text, QWidget *parent) +{ + QLabel *label = new QLabel(text, parent); + label->setAutoFillBackground(true); + label->setFrameShape(QFrame::Panel); + label->setFrameShadow(QFrame::Raised); + return label; +} + +static QString hotSpotMimeDataKey() { return QStringLiteral("application/x-hotspot"); } + DragWidget::DragWidget(QWidget *parent) : QWidget(parent) { - QFile dictionaryFile(":/dictionary/words.txt"); + QFile dictionaryFile(QStringLiteral(":/dictionary/words.txt")); dictionaryFile.open(QIODevice::ReadOnly); QTextStream inputStream(&dictionaryFile); @@ -57,7 +67,7 @@ DragWidget::DragWidget(QWidget *parent) QString word; inputStream >> word; if (!word.isEmpty()) { - DragLabel *wordLabel = new DragLabel(word, this); + QLabel *wordLabel = createDragLabel(word, this); wordLabel->move(x, y); wordLabel->show(); wordLabel->setAttribute(Qt::WA_DeleteOnClose); @@ -69,12 +79,6 @@ DragWidget::DragWidget(QWidget *parent) } } - /* - QPalette newPalette = palette(); - newPalette.setColor(QPalette::Window, Qt::white); - setPalette(newPalette); - */ - setAcceptDrops(true); setMinimumSize(400, qMax(200, y)); setWindowTitle(tr("Draggable Text")); @@ -98,19 +102,19 @@ void DragWidget::dropEvent(QDropEvent *event) { if (event->mimeData()->hasText()) { const QMimeData *mime = event->mimeData(); - QStringList pieces = mime->text().split(QRegExp("\\s+"), + QStringList pieces = mime->text().split(QRegularExpression(QStringLiteral("\\s+")), QString::SkipEmptyParts); QPoint position = event->pos(); QPoint hotSpot; - QList<QByteArray> hotSpotPos = mime->data("application/x-hotspot").split(' '); + QByteArrayList hotSpotPos = mime->data(hotSpotMimeDataKey()).split(' '); if (hotSpotPos.size() == 2) { hotSpot.setX(hotSpotPos.first().toInt()); hotSpot.setY(hotSpotPos.last().toInt()); } - foreach (QString piece, pieces) { - DragLabel *newLabel = new DragLabel(piece, this); + foreach (const QString &piece, pieces) { + QLabel *newLabel = createDragLabel(piece, this); newLabel->move(position - hotSpot); newLabel->show(); newLabel->setAttribute(Qt::WA_DeleteOnClose); @@ -127,18 +131,15 @@ void DragWidget::dropEvent(QDropEvent *event) } else { event->ignore(); } - foreach (QObject *child, children()) { - if (child->inherits("QWidget")) { - QWidget *widget = static_cast<QWidget *>(child); - if (!widget->isVisible()) - widget->deleteLater(); - } + foreach (QWidget *widget, findChildren<QWidget *>()) { + if (!widget->isVisible()) + widget->deleteLater(); } } void DragWidget::mousePressEvent(QMouseEvent *event) { - QLabel *child = static_cast<QLabel*>(childAt(event->pos())); + QLabel *child = qobject_cast<QLabel*>(childAt(event->pos())); if (!child) return; @@ -146,8 +147,8 @@ void DragWidget::mousePressEvent(QMouseEvent *event) QMimeData *mimeData = new QMimeData; mimeData->setText(child->text()); - mimeData->setData("application/x-hotspot", - QByteArray::number(hotSpot.x()) + " " + QByteArray::number(hotSpot.y())); + mimeData->setData(hotSpotMimeDataKey(), + QByteArray::number(hotSpot.x()) + ' ' + QByteArray::number(hotSpot.y())); QPixmap pixmap(child->size()); child->render(&pixmap); diff --git a/examples/widgets/draganddrop/dropsite/droparea.cpp b/examples/widgets/draganddrop/dropsite/droparea.cpp index d3d2bb10ca..0016434cc3 100644 --- a/examples/widgets/draganddrop/dropsite/droparea.cpp +++ b/examples/widgets/draganddrop/dropsite/droparea.cpp @@ -92,10 +92,8 @@ void DropArea::dropEvent(QDropEvent *event) } else if (mimeData->hasUrls()) { QList<QUrl> urlList = mimeData->urls(); QString text; - for (int i = 0; i < urlList.size() && i < 32; ++i) { - QString url = urlList.at(i).path(); - text += url + QString("\n"); - } + for (int i = 0; i < urlList.size() && i < 32; ++i) + text += urlList.at(i).path() + QLatin1Char('\n'); setText(text); } else { setText(tr("Cannot display data")); diff --git a/examples/widgets/draganddrop/dropsite/dropsitewindow.cpp b/examples/widgets/draganddrop/dropsite/dropsitewindow.cpp index 5f0e689fc9..5d48be1c34 100644 --- a/examples/widgets/draganddrop/dropsite/dropsitewindow.cpp +++ b/examples/widgets/draganddrop/dropsite/dropsitewindow.cpp @@ -55,8 +55,8 @@ DropSiteWindow::DropSiteWindow() //! [constructor part2] dropArea = new DropArea; - connect(dropArea, SIGNAL(changed(const QMimeData*)), - this, SLOT(updateFormatsTable(const QMimeData*))); + connect(dropArea, &DropArea::changed, + this, &DropSiteWindow::updateFormatsTable); //! [constructor part2] //! [constructor part3] @@ -78,17 +78,16 @@ DropSiteWindow::DropSiteWindow() buttonBox->addButton(clearButton, QDialogButtonBox::ActionRole); buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole); - connect(quitButton, SIGNAL(pressed()), this, SLOT(close())); - connect(clearButton, SIGNAL(pressed()), dropArea, SLOT(clear())); + connect(quitButton, &QAbstractButton::pressed, this, &QWidget::close); + connect(clearButton, &QAbstractButton::pressed, dropArea, &DropArea::clear); //! [constructor part4] //! [constructor part5] - QVBoxLayout *mainLayout = new QVBoxLayout; + QVBoxLayout *mainLayout = new QVBoxLayout(this); mainLayout->addWidget(abstractLabel); mainLayout->addWidget(dropArea); mainLayout->addWidget(formatsTable); mainLayout->addWidget(buttonBox); - setLayout(mainLayout); setWindowTitle(tr("Drop Site")); setMinimumSize(350, 500); @@ -112,22 +111,18 @@ void DropSiteWindow::updateFormatsTable(const QMimeData *mimeData) //! [updateFormatsTable() part3] QString text; - if (format == "text/plain") { + if (format == QLatin1String("text/plain")) { text = mimeData->text().simplified(); - } else if (format == "text/html") { + } else if (format == QLatin1String("text/html")) { text = mimeData->html().simplified(); - } else if (format == "text/uri-list") { + } else if (format == QLatin1String("text/uri-list")) { QList<QUrl> urlList = mimeData->urls(); for (int i = 0; i < urlList.size() && i < 32; ++i) - text.append(urlList[i].toString() + " "); + text.append(urlList.at(i).toString() + QLatin1Char(' ')); } else { QByteArray data = mimeData->data(format); - for (int i = 0; i < data.size() && i < 32; ++i) { - QString hex = QString("%1").arg(uchar(data[i]), 2, 16, - QChar('0')) - .toUpper(); - text.append(hex + " "); - } + for (int i = 0; i < data.size() && i < 32; ++i) + text.append(QStringLiteral("%1 ").arg(uchar(data[i]), 2, 16, QLatin1Char('0')).toUpper()); } //! [updateFormatsTable() part3] diff --git a/examples/widgets/draganddrop/fridgemagnets/dragwidget.cpp b/examples/widgets/draganddrop/fridgemagnets/dragwidget.cpp index a591a29994..3a9ab5fa76 100644 --- a/examples/widgets/draganddrop/fridgemagnets/dragwidget.cpp +++ b/examples/widgets/draganddrop/fridgemagnets/dragwidget.cpp @@ -43,11 +43,13 @@ #include <QtWidgets> +static inline QString fridgetMagnetsMimeType() { return QStringLiteral("application/x-fridgemagnet"); } + //! [0] DragWidget::DragWidget(QWidget *parent) : QWidget(parent) { - QFile dictionaryFile(":/dictionary/words.txt"); + QFile dictionaryFile(QStringLiteral(":/dictionary/words.txt")); dictionaryFile.open(QFile::ReadOnly); QTextStream inputStream(&dictionaryFile); //! [0] @@ -74,7 +76,6 @@ DragWidget::DragWidget(QWidget *parent) //! [1] //! [2] - //Fridge magnets is used for demoing Qt on S60 and themed backgrounds look better than white QPalette newPalette = palette(); newPalette.setColor(QPalette::Window, Qt::white); setPalette(newPalette); @@ -90,7 +91,7 @@ DragWidget::DragWidget(QWidget *parent) void DragWidget::dragEnterEvent(QDragEnterEvent *event) { //! [4] //! [5] - if (event->mimeData()->hasFormat("application/x-fridgemagnet")) { + if (event->mimeData()->hasFormat(fridgetMagnetsMimeType())) { if (children().contains(event->source())) { event->setDropAction(Qt::MoveAction); event->accept(); @@ -110,7 +111,7 @@ void DragWidget::dragEnterEvent(QDragEnterEvent *event) //! [8] void DragWidget::dragMoveEvent(QDragMoveEvent *event) { - if (event->mimeData()->hasFormat("application/x-fridgemagnet")) { + if (event->mimeData()->hasFormat(fridgetMagnetsMimeType())) { if (children().contains(event->source())) { event->setDropAction(Qt::MoveAction); event->accept(); @@ -128,10 +129,10 @@ void DragWidget::dragMoveEvent(QDragMoveEvent *event) //! [9] void DragWidget::dropEvent(QDropEvent *event) { - if (event->mimeData()->hasFormat("application/x-fridgemagnet")) { + if (event->mimeData()->hasFormat(fridgetMagnetsMimeType())) { const QMimeData *mime = event->mimeData(); //! [9] //! [10] - QByteArray itemData = mime->data("application/x-fridgemagnet"); + QByteArray itemData = mime->data(fridgetMagnetsMimeType()); QDataStream dataStream(&itemData, QIODevice::ReadOnly); QString text; @@ -152,11 +153,11 @@ void DragWidget::dropEvent(QDropEvent *event) } //! [11] //! [12] } else if (event->mimeData()->hasText()) { - QStringList pieces = event->mimeData()->text().split(QRegExp("\\s+"), + QStringList pieces = event->mimeData()->text().split(QRegularExpression(QStringLiteral("\\s+")), QString::SkipEmptyParts); QPoint position = event->pos(); - foreach (QString piece, pieces) { + foreach (const QString &piece, pieces) { DragLabel *newLabel = new DragLabel(piece, this); newLabel->move(position); newLabel->show(); @@ -190,7 +191,7 @@ void DragWidget::mousePressEvent(QMouseEvent *event) //! [15] QMimeData *mimeData = new QMimeData; - mimeData->setData("application/x-fridgemagnet", itemData); + mimeData->setData(fridgetMagnetsMimeType(), itemData); mimeData->setText(child->labelText()); //! [15] diff --git a/examples/widgets/draganddrop/fridgemagnets/main.cpp b/examples/widgets/draganddrop/fridgemagnets/main.cpp index edff4486d6..a52ff8cabd 100644 --- a/examples/widgets/draganddrop/fridgemagnets/main.cpp +++ b/examples/widgets/draganddrop/fridgemagnets/main.cpp @@ -52,7 +52,7 @@ int main(int argc, char *argv[]) #endif DragWidget window; - bool smallScreen = QApplication::arguments().contains("-small-screen"); + bool smallScreen = QApplication::arguments().contains(QStringLiteral("-small-screen")); if (smallScreen) window.showFullScreen(); else diff --git a/examples/widgets/draganddrop/puzzle/main.cpp b/examples/widgets/draganddrop/puzzle/main.cpp index 706ebe4d70..e8ecbe37db 100644 --- a/examples/widgets/draganddrop/puzzle/main.cpp +++ b/examples/widgets/draganddrop/puzzle/main.cpp @@ -48,7 +48,7 @@ int main(int argc, char *argv[]) QApplication app(argc, argv); MainWindow window; - window.openImage(":/images/example.jpg"); + window.loadImage(QStringLiteral(":/images/example.jpg")); window.show(); return app.exec(); } diff --git a/examples/widgets/draganddrop/puzzle/mainwindow.cpp b/examples/widgets/draganddrop/puzzle/mainwindow.cpp index 0fbdfc3f8d..48e79946e7 100644 --- a/examples/widgets/draganddrop/puzzle/mainwindow.cpp +++ b/examples/widgets/draganddrop/puzzle/mainwindow.cpp @@ -55,26 +55,27 @@ MainWindow::MainWindow(QWidget *parent) setWindowTitle(tr("Puzzle")); } -void MainWindow::openImage(const QString &path) +void MainWindow::openImage() { - QString fileName = path; + const QString fileName = + QFileDialog::getOpenFileName(this, tr("Open Image"), QString(), + tr("Image Files (*.png *.jpg *.bmp)")); - if (fileName.isNull()) { - fileName = QFileDialog::getOpenFileName(this, - tr("Open Image"), "", "Image Files (*.png *.jpg *.bmp)"); - } + if (!fileName.isEmpty()) + loadImage(fileName); +} - if (!fileName.isEmpty()) { - QPixmap newImage; - if (!newImage.load(fileName)) { - QMessageBox::warning(this, tr("Open Image"), - tr("The image file could not be loaded."), - QMessageBox::Cancel); - return; - } - puzzleImage = newImage; - setupPuzzle(); +void MainWindow::loadImage(const QString &fileName) +{ + QPixmap newImage; + if (!newImage.load(fileName)) { + QMessageBox::warning(this, tr("Open Image"), + tr("The image file could not be loaded."), + QMessageBox::Close); + return; } + puzzleImage = newImage; + setupPuzzle(); } void MainWindow::setCompleted() @@ -120,19 +121,15 @@ void MainWindow::setupMenus() { QMenu *fileMenu = menuBar()->addMenu(tr("&File")); - QAction *openAction = fileMenu->addAction(tr("&Open...")); + QAction *openAction = fileMenu->addAction(tr("&Open..."), this, &MainWindow::openImage); openAction->setShortcuts(QKeySequence::Open); - QAction *exitAction = fileMenu->addAction(tr("E&xit")); + QAction *exitAction = fileMenu->addAction(tr("E&xit"), qApp, &QCoreApplication::quit); exitAction->setShortcuts(QKeySequence::Quit); QMenu *gameMenu = menuBar()->addMenu(tr("&Game")); - QAction *restartAction = gameMenu->addAction(tr("&Restart")); - - connect(openAction, SIGNAL(triggered()), this, SLOT(openImage())); - connect(exitAction, SIGNAL(triggered()), qApp, SLOT(quit())); - connect(restartAction, SIGNAL(triggered()), this, SLOT(setupPuzzle())); + gameMenu->addAction(tr("&Restart"), this, &MainWindow::setupPuzzle); } void MainWindow::setupWidgets() @@ -144,8 +141,8 @@ void MainWindow::setupWidgets() piecesList = new PiecesList(puzzleWidget->pieceSize(), this); - connect(puzzleWidget, SIGNAL(puzzleCompleted()), - this, SLOT(setCompleted()), Qt::QueuedConnection); + connect(puzzleWidget, &PuzzleWidget::puzzleCompleted, + this, &MainWindow::setCompleted, Qt::QueuedConnection); frameLayout->addWidget(piecesList); frameLayout->addWidget(puzzleWidget); diff --git a/examples/widgets/draganddrop/puzzle/mainwindow.h b/examples/widgets/draganddrop/puzzle/mainwindow.h index 093a14472e..b5b7d0d903 100644 --- a/examples/widgets/draganddrop/puzzle/mainwindow.h +++ b/examples/widgets/draganddrop/puzzle/mainwindow.h @@ -56,9 +56,10 @@ class MainWindow : public QMainWindow public: MainWindow(QWidget *parent = 0); + void loadImage(const QString &path); public slots: - void openImage(const QString &path = QString()); + void openImage(); void setupPuzzle(); private slots: diff --git a/examples/widgets/draganddrop/puzzle/pieceslist.cpp b/examples/widgets/draganddrop/puzzle/pieceslist.cpp index e60fd0a9ff..fb27aa2304 100644 --- a/examples/widgets/draganddrop/puzzle/pieceslist.cpp +++ b/examples/widgets/draganddrop/puzzle/pieceslist.cpp @@ -57,7 +57,7 @@ PiecesList::PiecesList(int pieceSize, QWidget *parent) void PiecesList::dragEnterEvent(QDragEnterEvent *event) { - if (event->mimeData()->hasFormat("image/x-puzzle-piece")) + if (event->mimeData()->hasFormat(PiecesList::puzzleMimeType())) event->accept(); else event->ignore(); @@ -65,7 +65,7 @@ void PiecesList::dragEnterEvent(QDragEnterEvent *event) void PiecesList::dragMoveEvent(QDragMoveEvent *event) { - if (event->mimeData()->hasFormat("image/x-puzzle-piece")) { + if (event->mimeData()->hasFormat(PiecesList::puzzleMimeType())) { event->setDropAction(Qt::MoveAction); event->accept(); } else { @@ -75,8 +75,8 @@ void PiecesList::dragMoveEvent(QDragMoveEvent *event) void PiecesList::dropEvent(QDropEvent *event) { - if (event->mimeData()->hasFormat("image/x-puzzle-piece")) { - QByteArray pieceData = event->mimeData()->data("image/x-puzzle-piece"); + if (event->mimeData()->hasFormat(PiecesList::puzzleMimeType())) { + QByteArray pieceData = event->mimeData()->data(PiecesList::puzzleMimeType()); QDataStream dataStream(&pieceData, QIODevice::ReadOnly); QPixmap pixmap; QPoint location; @@ -112,7 +112,7 @@ void PiecesList::startDrag(Qt::DropActions /*supportedActions*/) dataStream << pixmap << location; QMimeData *mimeData = new QMimeData; - mimeData->setData("image/x-puzzle-piece", itemData); + mimeData->setData(PiecesList::puzzleMimeType(), itemData); QDrag *drag = new QDrag(this); drag->setMimeData(mimeData); diff --git a/examples/widgets/draganddrop/puzzle/pieceslist.h b/examples/widgets/draganddrop/puzzle/pieceslist.h index 83c1ad8285..07fa504f41 100644 --- a/examples/widgets/draganddrop/puzzle/pieceslist.h +++ b/examples/widgets/draganddrop/puzzle/pieceslist.h @@ -51,6 +51,8 @@ public: explicit PiecesList(int pieceSize, QWidget *parent = 0); void addPiece(QPixmap pixmap, QPoint location); + static QString puzzleMimeType() { return QStringLiteral("image/x-puzzle-piece"); } + protected: void dragEnterEvent(QDragEnterEvent *event) Q_DECL_OVERRIDE; void dragMoveEvent(QDragMoveEvent *event) Q_DECL_OVERRIDE; diff --git a/examples/widgets/draganddrop/puzzle/puzzlewidget.cpp b/examples/widgets/draganddrop/puzzle/puzzlewidget.cpp index 69c0cbf0cc..29052da4fb 100644 --- a/examples/widgets/draganddrop/puzzle/puzzlewidget.cpp +++ b/examples/widgets/draganddrop/puzzle/puzzlewidget.cpp @@ -39,6 +39,7 @@ ****************************************************************************/ #include "puzzlewidget.h" +#include "pieceslist.h" #include <QDrag> #include <QDragEnterEvent> @@ -65,7 +66,7 @@ void PuzzleWidget::clear() void PuzzleWidget::dragEnterEvent(QDragEnterEvent *event) { - if (event->mimeData()->hasFormat("image/x-puzzle-piece")) + if (event->mimeData()->hasFormat(PiecesList::puzzleMimeType())) event->accept(); else event->ignore(); @@ -83,8 +84,8 @@ void PuzzleWidget::dragMoveEvent(QDragMoveEvent *event) { QRect updateRect = highlightedRect.united(targetSquare(event->pos())); - if (event->mimeData()->hasFormat("image/x-puzzle-piece") - && findPiece(targetSquare(event->pos())) == -1) { + if (event->mimeData()->hasFormat(PiecesList::puzzleMimeType()) + && pieceRects.indexOf(targetSquare(event->pos())) == -1) { highlightedRect = targetSquare(event->pos()); event->setDropAction(Qt::MoveAction); @@ -99,10 +100,10 @@ void PuzzleWidget::dragMoveEvent(QDragMoveEvent *event) void PuzzleWidget::dropEvent(QDropEvent *event) { - if (event->mimeData()->hasFormat("image/x-puzzle-piece") - && findPiece(targetSquare(event->pos())) == -1) { + if (event->mimeData()->hasFormat(PiecesList::puzzleMimeType()) + && pieceRects.indexOf(targetSquare(event->pos())) == -1) { - QByteArray pieceData = event->mimeData()->data("image/x-puzzle-piece"); + QByteArray pieceData = event->mimeData()->data(PiecesList::puzzleMimeType()); QDataStream dataStream(&pieceData, QIODevice::ReadOnly); QRect square = targetSquare(event->pos()); QPixmap pixmap; @@ -130,19 +131,10 @@ void PuzzleWidget::dropEvent(QDropEvent *event) } } -int PuzzleWidget::findPiece(const QRect &pieceRect) const -{ - for (int i = 0; i < pieceRects.size(); ++i) { - if (pieceRect == pieceRects[i]) - return i; - } - return -1; -} - void PuzzleWidget::mousePressEvent(QMouseEvent *event) { QRect square = targetSquare(event->pos()); - int found = findPiece(square); + int found = pieceRects.indexOf(square); if (found == -1) return; @@ -164,7 +156,7 @@ void PuzzleWidget::mousePressEvent(QMouseEvent *event) dataStream << pixmap << location; QMimeData *mimeData = new QMimeData; - mimeData->setData("image/x-puzzle-piece", itemData); + mimeData->setData(PiecesList::puzzleMimeType(), itemData); QDrag *drag = new QDrag(this); drag->setMimeData(mimeData); diff --git a/examples/widgets/draganddrop/puzzle/puzzlewidget.h b/examples/widgets/draganddrop/puzzle/puzzlewidget.h index 6bf264b5e0..eb8a3a29f9 100644 --- a/examples/widgets/draganddrop/puzzle/puzzlewidget.h +++ b/examples/widgets/draganddrop/puzzle/puzzlewidget.h @@ -75,7 +75,6 @@ protected: void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE; private: - int findPiece(const QRect &pieceRect) const; const QRect targetSquare(const QPoint &position) const; QList<QPixmap> piecePixmaps; diff --git a/examples/widgets/gestures/imagegestures/imagewidget.cpp b/examples/widgets/gestures/imagegestures/imagewidget.cpp index 440eb783c1..28c715c688 100644 --- a/examples/widgets/gestures/imagegestures/imagewidget.cpp +++ b/examples/widgets/gestures/imagegestures/imagewidget.cpp @@ -200,7 +200,6 @@ void ImageWidget::openDirectory(const QString &path) QImage ImageWidget::loadImage(const QString &fileName) { - qDebug() << position << files << fileName; QImageReader reader(fileName); reader.setAutoTransform(true); qCDebug(lcExample) << "loading" << QDir::toNativeSeparators(fileName) << position << '/' << files.size(); @@ -230,7 +229,7 @@ void ImageWidget::goNextImage() prevImage = currentImage; currentImage = nextImage; if (position+1 < files.size()) - nextImage = loadImage(path+QLatin1String("/")+files.at(position+1)); + nextImage = loadImage(path + QLatin1Char('/') + files.at(position+1)); else nextImage = QImage(); } @@ -247,7 +246,7 @@ void ImageWidget::goPrevImage() nextImage = currentImage; currentImage = prevImage; if (position > 0) - prevImage = loadImage(path+QLatin1String("/")+files.at(position-1)); + prevImage = loadImage(path + QLatin1Char('/') + files.at(position-1)); else prevImage = QImage(); } @@ -277,12 +276,12 @@ void ImageWidget::goToImage(int index) position = index; if (index > 0) - prevImage = loadImage(path+QLatin1String("/")+files.at(position-1)); + prevImage = loadImage(path + QLatin1Char('/') + files.at(position-1)); else prevImage = QImage(); - currentImage = loadImage(path+QLatin1String("/")+files.at(position)); + currentImage = loadImage(path + QLatin1Char('/') + files.at(position)); if (position+1 < files.size()) - nextImage = loadImage(path+QLatin1String("/")+files.at(position+1)); + nextImage = loadImage(path + QLatin1Char('/') + files.at(position+1)); else nextImage = QImage(); update(); diff --git a/examples/widgets/gestures/imagegestures/imagewidget.h b/examples/widgets/gestures/imagegestures/imagewidget.h index 1629516c0a..71ad2792d0 100644 --- a/examples/widgets/gestures/imagegestures/imagewidget.h +++ b/examples/widgets/gestures/imagegestures/imagewidget.h @@ -77,7 +77,6 @@ private: void swipeTriggered(QSwipeGesture*); //! [class definition begin] - void updateImage(); QImage loadImage(const QString &fileName); void loadImage(); void goNextImage(); diff --git a/examples/widgets/gestures/imagegestures/mainwidget.h b/examples/widgets/gestures/imagegestures/mainwidget.h index 20e32d1afb..e37baa398c 100644 --- a/examples/widgets/gestures/imagegestures/mainwidget.h +++ b/examples/widgets/gestures/imagegestures/mainwidget.h @@ -57,8 +57,6 @@ public slots: void openDirectory(const QString &path); private: - bool loadImage(const QString &fileName); - ImageWidget *imageWidget; }; diff --git a/examples/widgets/graphicsview/boxes/scene.cpp b/examples/widgets/graphicsview/boxes/scene.cpp index 48bdcb9d93..c9691704cb 100644 --- a/examples/widgets/graphicsview/boxes/scene.cpp +++ b/examples/widgets/graphicsview/boxes/scene.cpp @@ -319,9 +319,9 @@ RenderOptionsDialog::RenderOptionsDialog() while (++it != tokens.end()) { m_parameterNames << name; if (!singleElement) { - m_parameterNames.back() += "["; + m_parameterNames.back() += '['; m_parameterNames.back() += counter + counterPos; - m_parameterNames.back() += "]"; + m_parameterNames.back() += ']'; int j = 8; // position of last digit ++counter[j]; while (j > 0 && counter[j] > '9') { diff --git a/examples/widgets/itemviews/chart/mainwindow.cpp b/examples/widgets/itemviews/chart/mainwindow.cpp index 9a3b372233..a148c3036d 100644 --- a/examples/widgets/itemviews/chart/mainwindow.cpp +++ b/examples/widgets/itemviews/chart/mainwindow.cpp @@ -124,7 +124,7 @@ void MainWindow::loadFile(const QString &fileName) if (!line.isEmpty()) { model->insertRows(row, 1, QModelIndex()); - QStringList pieces = line.split(",", QString::SkipEmptyParts); + QStringList pieces = line.split(',', QString::SkipEmptyParts); model->setData(model->index(row, 0, QModelIndex()), pieces.value(0)); model->setData(model->index(row, 1, QModelIndex()), diff --git a/examples/widgets/itemviews/editabletreemodel/treemodel.cpp b/examples/widgets/itemviews/editabletreemodel/treemodel.cpp index 2903dd7d38..2b12c142cd 100644 --- a/examples/widgets/itemviews/editabletreemodel/treemodel.cpp +++ b/examples/widgets/itemviews/editabletreemodel/treemodel.cpp @@ -246,7 +246,7 @@ void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent) while (number < lines.count()) { int position = 0; while (position < lines[number].length()) { - if (lines[number].mid(position, 1) != " ") + if (lines[number].at(position) != ' ') break; ++position; } diff --git a/examples/widgets/itemviews/frozencolumn/main.cpp b/examples/widgets/itemviews/frozencolumn/main.cpp index cfdf57135c..1292a7f403 100644 --- a/examples/widgets/itemviews/frozencolumn/main.cpp +++ b/examples/widgets/itemviews/frozencolumn/main.cpp @@ -54,15 +54,15 @@ int main(int argc, char* argv[]) QFile file(":/grades.txt"); if (file.open(QFile::ReadOnly)) { QString line = file.readLine(200); - QStringList list = line.simplified().split(","); + QStringList list = line.simplified().split(','); model->setHorizontalHeaderLabels(list); int row = 0; QStandardItem *newItem = 0; while (file.canReadLine()) { line = file.readLine(200); - if (!line.startsWith("#") && line.contains(",")) { - list= line.simplified().split(","); + if (!line.startsWith('#') && line.contains(',')) { + list = line.simplified().split(','); for (int col = 0; col < list.length(); ++col){ newItem = new QStandardItem(list.at(col)); model->setItem(row, col, newItem); diff --git a/examples/widgets/itemviews/interview/model.cpp b/examples/widgets/itemviews/interview/model.cpp index ba65144cfa..efbb67486b 100644 --- a/examples/widgets/itemviews/interview/model.cpp +++ b/examples/widgets/itemviews/interview/model.cpp @@ -88,7 +88,7 @@ QVariant Model::data(const QModelIndex &index, int role) const if (!index.isValid()) return QVariant(); if (role == Qt::DisplayRole) - return QVariant("Item " + QString::number(index.row()) + ":" + QString::number(index.column())); + return QVariant("Item " + QString::number(index.row()) + ':' + QString::number(index.column())); if (role == Qt::DecorationRole) { if (index.column() == 0) return iconProvider.icon(QFileIconProvider::Folder); diff --git a/examples/widgets/itemviews/simpledommodel/dommodel.cpp b/examples/widgets/itemviews/simpledommodel/dommodel.cpp index f6450abc8b..531957f60b 100644 --- a/examples/widgets/itemviews/simpledommodel/dommodel.cpp +++ b/examples/widgets/itemviews/simpledommodel/dommodel.cpp @@ -88,7 +88,7 @@ QVariant DomModel::data(const QModelIndex &index, int role) const for (int i = 0; i < attributeMap.count(); ++i) { QDomNode attribute = attributeMap.item(i); attributes << attribute.nodeName() + "=\"" - +attribute.nodeValue() + "\""; + +attribute.nodeValue() + '"'; } return attributes.join(' '); case 2: diff --git a/examples/widgets/itemviews/simpletreemodel/treemodel.cpp b/examples/widgets/itemviews/simpletreemodel/treemodel.cpp index aaa4685b27..f5cd1a160e 100644 --- a/examples/widgets/itemviews/simpletreemodel/treemodel.cpp +++ b/examples/widgets/itemviews/simpletreemodel/treemodel.cpp @@ -180,7 +180,7 @@ void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent) while (number < lines.count()) { int position = 0; while (position < lines[number].length()) { - if (lines[number].mid(position, 1) != " ") + if (lines[number].at(position) != ' ') break; position++; } diff --git a/examples/widgets/tools/regexp/regexpdialog.cpp b/examples/widgets/tools/regexp/regexpdialog.cpp index 32df8a4b91..8ed1e790fb 100644 --- a/examples/widgets/tools/regexp/regexpdialog.cpp +++ b/examples/widgets/tools/regexp/regexpdialog.cpp @@ -153,8 +153,8 @@ void RegExpDialog::refresh() QString escaped = pattern; escaped.replace("\\", "\\\\"); escaped.replace("\"", "\\\""); - escaped.prepend("\""); - escaped.append("\""); + escaped.prepend('"'); + escaped.append('"'); escapedPatternLineEdit->setText(escaped); QRegExp rx(pattern); diff --git a/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp b/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp index d40b4b325d..6cddc1f6c1 100644 --- a/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp +++ b/examples/widgets/tools/regularexpression/regularexpressiondialog.cpp @@ -111,8 +111,8 @@ void RegularExpressionDialog::refresh() QString escaped = pattern; escaped.replace(QLatin1String("\\"), QLatin1String("\\\\")); escaped.replace(QLatin1String("\""), QLatin1String("\\\"")); - escaped.prepend(QLatin1String("\"")); - escaped.append(QLatin1String("\"")); + escaped.prepend(QLatin1Char('"')); + escaped.append(QLatin1Char('"')); escapedPatternLineEdit->setText(escaped); QRegularExpression rx(pattern); diff --git a/examples/widgets/tools/settingseditor/variantdelegate.cpp b/examples/widgets/tools/settingseditor/variantdelegate.cpp index f68082c660..fe2391762b 100644 --- a/examples/widgets/tools/settingseditor/variantdelegate.cpp +++ b/examples/widgets/tools/settingseditor/variantdelegate.cpp @@ -60,7 +60,7 @@ VariantDelegate::VariantDelegate(QObject *parent) dateExp.setPattern("([0-9]{,4})-([0-9]{,2})-([0-9]{,2})"); timeExp.setPattern("([0-9]{,2}):([0-9]{,2}):([0-9]{,2})"); - dateTimeExp.setPattern(dateExp.pattern() + "T" + timeExp.pattern()); + dateTimeExp.setPattern(dateExp.pattern() + 'T' + timeExp.pattern()); } void VariantDelegate::paint(QPainter *painter, @@ -217,7 +217,7 @@ void VariantDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, value = QSize(sizeExp.cap(1).toInt(), sizeExp.cap(2).toInt()); break; case QVariant::StringList: - value = text.split(","); + value = text.split(','); break; case QVariant::Time: { diff --git a/examples/widgets/tutorials/addressbook/part7/addressbook.cpp b/examples/widgets/tutorials/addressbook/part7/addressbook.cpp index 6764423d71..2953ecd7de 100644 --- a/examples/widgets/tutorials/addressbook/part7/addressbook.cpp +++ b/examples/widgets/tutorials/addressbook/part7/addressbook.cpp @@ -421,23 +421,23 @@ void AddressBook::exportAsVCard() //! [export function part2] //! [export function part3] - out << "BEGIN:VCARD" << "\n"; - out << "VERSION:2.1" << "\n"; - out << "N:" << lastName << ";" << firstName << "\n"; + out << "BEGIN:VCARD" << '\n'; + out << "VERSION:2.1" << '\n'; + out << "N:" << lastName << ';' << firstName << '\n'; if (!nameList.isEmpty()) - out << "FN:" << nameList.join(' ') << "\n"; + out << "FN:" << nameList.join(' ') << '\n'; else - out << "FN:" << firstName << "\n"; + out << "FN:" << firstName << '\n'; //! [export function part3] //! [export function part4] address.replace(";", "\\;", Qt::CaseInsensitive); - address.replace("\n", ";", Qt::CaseInsensitive); + address.replace('\n', ";", Qt::CaseInsensitive); address.replace(",", " ", Qt::CaseInsensitive); - out << "ADR;HOME:;" << address << "\n"; - out << "END:VCARD" << "\n"; + out << "ADR;HOME:;" << address << '\n'; + out << "END:VCARD" << '\n'; QMessageBox::information(this, tr("Export Successful"), tr("\"%1\" has been exported as a vCard.").arg(name)); diff --git a/examples/widgets/tutorials/modelview/5_edit/mymodel.cpp b/examples/widgets/tutorials/modelview/5_edit/mymodel.cpp index 5eb677bb9d..c04c77772f 100644 --- a/examples/widgets/tutorials/modelview/5_edit/mymodel.cpp +++ b/examples/widgets/tutorials/modelview/5_edit/mymodel.cpp @@ -83,7 +83,7 @@ bool MyModel::setData(const QModelIndex & index, const QVariant & value, int rol { for(int col= 0; col < COLS; col++) { - result += m_gridData[row][col] + " "; + result += m_gridData[row][col] + ' '; } } emit editCompleted( result ); diff --git a/examples/widgets/widgets/calculator/calculator.cpp b/examples/widgets/widgets/calculator/calculator.cpp index e76011ee0d..87061a9868 100644 --- a/examples/widgets/widgets/calculator/calculator.cpp +++ b/examples/widgets/widgets/calculator/calculator.cpp @@ -276,7 +276,7 @@ void Calculator::pointClicked() { if (waitingForOperand) display->setText("0"); - if (!display->text().contains(".")) + if (!display->text().contains('.')) display->setText(display->text() + tr(".")); waitingForOperand = false; } diff --git a/examples/widgets/widgets/stylesheet/mainwindow.cpp b/examples/widgets/widgets/stylesheet/mainwindow.cpp index a49c06dfd2..6d84897c77 100644 --- a/examples/widgets/widgets/stylesheet/mainwindow.cpp +++ b/examples/widgets/widgets/stylesheet/mainwindow.cpp @@ -67,7 +67,7 @@ void MainWindow::on_aboutAction_triggered() { QMessageBox::about(this, tr("About Style sheet"), tr("The <b>Style Sheet</b> example shows how widgets can be styled " - "using <a href=\"http://doc.qt.digia.com/4.5/stylesheet.html\">Qt " + "using <a href=\"http://doc.qt.io/qt-5/stylesheet.html\">Qt " "Style Sheets</a>. Click <b>File|Edit Style Sheet</b> to pop up the " "style editor, and either choose an existing style sheet or design " "your own.")); diff --git a/examples/xml/htmlinfo/main.cpp b/examples/xml/htmlinfo/main.cpp index 3869ca5472..1424cfca67 100644 --- a/examples/xml/htmlinfo/main.cpp +++ b/examples/xml/htmlinfo/main.cpp @@ -79,7 +79,7 @@ void parseHtmlFile(QTextStream &out, const QString &fileName) { } //! [2] - out << " Title: \"" << title << "\"" << endl + out << " Title: \"" << title << '"' << endl << " Number of paragraphs: " << paragraphCount << endl << " Number of links: " << links.size() << endl << " Showing first few links:" << endl; diff --git a/examples/xml/saxbookmarks/xbelgenerator.cpp b/examples/xml/saxbookmarks/xbelgenerator.cpp index 24612c132c..5f1ec62e7e 100644 --- a/examples/xml/saxbookmarks/xbelgenerator.cpp +++ b/examples/xml/saxbookmarks/xbelgenerator.cpp @@ -81,8 +81,8 @@ QString XbelGenerator::escapedAttribute(const QString &str) { QString result = escapedText(str); result.replace("\"", """); - result.prepend("\""); - result.append("\""); + result.prepend(QLatin1Char('"')); + result.append(QLatin1Char('"')); return result; } |