diff options
126 files changed, 1991 insertions, 4669 deletions
@@ -1067,7 +1067,7 @@ CFG_DEFAULT_ANDROID_NDK_ROOT=$ANDROID_NDK_ROOT CFG_DEFAULT_ANDROID_SDK_ROOT=$ANDROID_SDK_ROOT CFG_DEFAULT_ANDROID_PLATFORM=android-9 CFG_DEFAULT_ANDROID_TARGET_ARCH=armeabi-v7a -CFG_DEFAULT_ANDROID_NDK_TOOLCHAIN_VERSION=4.7 +CFG_DEFAULT_ANDROID_NDK_TOOLCHAIN_VERSION=4.8 CFG_DEFAULT_ANDROID_NDK_HOST=$ANDROID_NDK_HOST if [ -d "$relpath/src/plugins/sqldrivers" ]; then diff --git a/examples/examples.pro b/examples/examples.pro index 7ba0de9438..b0f59c2020 100644 --- a/examples/examples.pro +++ b/examples/examples.pro @@ -7,6 +7,7 @@ SUBDIRS = \ gestures \ gui \ ipc \ + json \ network \ opengl \ qpa \ diff --git a/examples/json/json.pro b/examples/json/json.pro new file mode 100644 index 0000000000..af4d3e6f0f --- /dev/null +++ b/examples/json/json.pro @@ -0,0 +1,2 @@ +TEMPLATE = subdirs +SUBDIRS = savegame diff --git a/examples/widgets/tutorials/addressbook-fr/part6/finddialog.cpp b/examples/json/savegame/character.cpp index a5efb678c8..ef30f0eaf4 100644 --- a/examples/widgets/tutorials/addressbook-fr/part6/finddialog.cpp +++ b/examples/json/savegame/character.cpp @@ -38,45 +38,64 @@ ** ****************************************************************************/ -#include <QtWidgets> -#include "finddialog.h" +#include "character.h" -FindDialog::FindDialog(QWidget *parent) - : QDialog(parent) +Character::Character() : + mLevel(0), + mClassType(Warrior) { +} + +Character::Character(const QString &name, int level, Character::ClassType classType) : + mName(name), + mLevel(level), + mClassType(classType) +{ +} + +QString Character::name() const +{ + return mName; +} + +void Character::setName(const QString &name) { - QLabel *findLabel = new QLabel(tr("Enter the name of a contact:")); - lineEdit = new QLineEdit; + mName = name; +} - findButton = new QPushButton(tr("&Find")); - findText = ""; +int Character::level() const +{ + return mLevel; +} - QHBoxLayout *layout = new QHBoxLayout; - layout->addWidget(findLabel); - layout->addWidget(lineEdit); - layout->addWidget(findButton); +void Character::setLevel(int level) +{ + mLevel = level; +} - setLayout(layout); - setWindowTitle(tr("Find a Contact")); - connect(findButton, SIGNAL(clicked()), this, SLOT(findClicked())); - connect(findButton, SIGNAL(clicked()), this, SLOT(accept())); +Character::ClassType Character::classType() const +{ + return mClassType; } -void FindDialog::findClicked() +void Character::setClassType(Character::ClassType classType) { - QString text = lineEdit->text(); + mClassType = classType; +} - if (text.isEmpty()) { - QMessageBox::information(this, tr("Empty Field"), - tr("Please enter a name.")); - return; - } else { - findText = text; - lineEdit->clear(); - hide(); - } +//! [0] +void Character::read(const QJsonObject &json) +{ + mName = json["name"].toString(); + mLevel = json["level"].toDouble(); + mClassType = ClassType(qRound(json["classType"].toDouble())); } +//! [0] -QString FindDialog::getFindText() +//! [1] +void Character::write(QJsonObject &json) const { - return findText; + json["name"] = mName; + json["level"] = mLevel; + json["classType"] = mClassType; } +//! [1] diff --git a/examples/widgets/tutorials/addressbook-fr/part7/finddialog.h b/examples/json/savegame/character.h index 42ff91143e..32369820f4 100644 --- a/examples/widgets/tutorials/addressbook-fr/part7/finddialog.h +++ b/examples/json/savegame/character.h @@ -38,31 +38,39 @@ ** ****************************************************************************/ -#ifndef FINDDIALOG_H -#define FINDDIALOG_H +#ifndef CHARACTER_H +#define CHARACTER_H -#include <QDialog> +#include <QJsonObject> +#include <QString> -QT_BEGIN_NAMESPACE -class QLineEdit; -class QPushButton; -QT_END_NAMESPACE - -class FindDialog : public QDialog +//! [0] +class Character { - Q_OBJECT - public: - FindDialog(QWidget *parent = 0); - QString getFindText(); + enum ClassType { + Warrior, Mage, Archer + }; + + Character(); + Character(const QString &name, int level, ClassType classType); + + QString name() const; + void setName(const QString &name); + + int level() const; + void setLevel(int level); -public slots: - void findClicked(); + ClassType classType() const; + void setClassType(ClassType classType); + void read(const QJsonObject &json); + void write(QJsonObject &json) const; private: - QPushButton *findButton; - QLineEdit *lineEdit; - QString findText; + QString mName; + int mLevel; + ClassType mClassType; }; +//! [0] -#endif +#endif // CHARACTER_H diff --git a/examples/json/savegame/doc/src/savegame.qdoc b/examples/json/savegame/doc/src/savegame.qdoc new file mode 100644 index 0000000000..586c100399 --- /dev/null +++ b/examples/json/savegame/doc/src/savegame.qdoc @@ -0,0 +1,184 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 savegame + \title JSON Save Game Example + + \brief The JSON Save Game example demonstrates how to save and load a + small game using QJsonDocument, QJsonObject and QJsonArray. + + Many games provide save functionality, so that the player's progress through + the game can be saved and loaded at a later time. The process of saving a + game generally involves serializing each game object's member variables + to a file. Many formats can be used for this purpose, one of which is JSON. + With QJsonDocument, you also have the ability to serialize a document in a + binary format, which is great if you don't want the save file to be + readable, or if you need to keep the file size down. + + In this example, we'll demonstrate how to save and load a simple game to + and from JSON and binary formats. + + \section1 The Character class + + The Character class represents a non-player character (NPC) in our game, and + stores the player's name, level, and class type. + + It provides read() and write() functions to serialise its member variables. + + \snippet savegame/character.h 0 + + Of particular interest to us are the read and write function + implementations: + + \snippet savegame/character.cpp 0 + + In the read() function, we assign Character's members values from the + QJsonObject argument. You can use either \l QJsonObject::operator[]() or + QJsonObject::value() to access values within the JSON object; both are + const functions and return QJsonValue::Undefined if the key is invalid. We + could check if the keys are valid before attempting to read them with + QJsonObject::contains(), but we assume that they are. + + \snippet savegame/character.cpp 1 + + In the write() function, we do the reverse of the read() function; assign + values from the Character object to the JSON object. As with accessing + values, there are two ways to set values on a QJsonObject: + \l QJsonObject::operator[]() and QJsonObject::insert(). Both will override + any existing value at the given key. + + Next up is the Level class: + + \snippet savegame/level.h 0 + + We want to have several levels in our game, each with several NPCs, so we + keep a QList of Character objects. We also provide the familiar read() and + write() functions. + + \snippet savegame/level.cpp 0 + + Containers can be written and read to and from JSON using QJsonArray. In our + case, we construct a QJsonArray from the value associated with the key + \c "npcs". Then, for each QJsonValue element in the array, we call + toObject() to get the Character's JSON object. The Character object can then + read their JSON and be appended to our NPC list. + + \note \l{Container Classes}{Associate containers} can be written by storing + the key in each value object (if it's not already). With this approach, the + container is stored as a regular array of objects, but the index of each + element is used as the key to construct the container when reading it back + in. + + \snippet savegame/level.cpp 1 + + Again, the write() function is similar to the read() function, except + reversed. + + Having established the Character and Level classes, we can move on to + the Game class: + + \snippet savegame/game.h 0 + + First of all, we define the \c SaveFormat enum. This will allow us to + specify the format in which the game should be saved: \c Json or \c Binary. + + Next, we provide accessors for the player and levels. We then expose three + functions: newGame(), saveGame() and loadGame(). + + The read() and write() functions are used by saveGame() and loadGame(). + + \snippet savegame/game.cpp 0 + + To setup a new game, we create the player and populate the levels and their + NPCs. + + \snippet savegame/game.cpp 1 + + The first thing we do in the read() function is tell the player to read + itself. We then clear the levels list so that calling loadGame() on the same + Game object twice doesn't result in old levels hanging around. + + We then populate the level list by reading each Level from a QJsonArray. + + \snippet savegame/game.cpp 2 + + We write the game to JSON similarly to how we write Level. + + \snippet savegame/game.cpp 3 + + When loading a saved game in loadGame(), the first thing we do is open the + save file based on which format it was saved to; \c "save.json" for JSON, + and \c "save.dat" for binary. We print a warning and return \c false if the + file couldn't be opened. + + Since QJsonDocument's \l{QJsonDocument::fromJson()}{fromJson()} and + \l{QJsonDocument::fromBinaryData()}{fromBinaryData()} functions both take a + QByteArray, we can read the entire contents of the save file into one, + regardless of the save format. + + After constructing the QJsonDocument, we instruct the Game object to read + itself and then return \c true to indicate success. + + \snippet savegame/game.cpp 4 + + Not surprisingly, saveGame() looks very much like loadGame(). We determine + the file extension based on the format, print a warning and return \c false + if the opening of the file fails. We then write the Game object to a + QJsonDocument, and call either QJsonDocument::toJson() or to + QJsonDocument::toBinaryData() to save the game, depending on which format + was specified. + + We are now ready to enter main(): + + \snippet savegame/main.cpp 0 + + Since we're only interested in demonstrating \e serialization of a game with + JSON, our game is not actually playable. Therefore, we only need + QCoreApplication and have no event loop. We create our game and assume that + the player had a great time and made lots of progress, altering the internal + state of our Character, Level and Game objects. + + \snippet savegame/main.cpp 1 + + When the player has finished, we save their game. For demonstration + purposes, we serialize to both JSON and binary. You can examine the contents + of the files in the same directory as the executable, although the binary + save file will contain some garbage characters (which is normal). + + To show that the saved files can be loaded again, we call loadGame() for + each format, returning \c 1 on failure. Assuming everything went well, we + return \c 0 to indicate success. + + That concludes our example. As you can see, serialization with Qt's JSON + classes is very simple and convenient. The advantages of using QJsonDocument + and friends over QDataStream, for example, is that you not only get + human-readable JSON files, but you also have the option to use a binary + format if it's required, \e without rewriting any code. + + \sa {JSON Support in Qt}, {Data Storage} +*/ diff --git a/examples/json/savegame/game.cpp b/examples/json/savegame/game.cpp new file mode 100644 index 0000000000..a08071b208 --- /dev/null +++ b/examples/json/savegame/game.cpp @@ -0,0 +1,164 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** 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 Digia Plc and its Subsidiary(-ies) nor the names +** of its contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "game.h" + +#include <QFile> +#include <QJsonArray> +#include <QJsonDocument> + +Game::Game() +{ +} + +const Character &Game::player() const +{ + return mPlayer; +} + +const QList<Level> &Game::levels() const { + return mLevels; +} + +//! [0] +void Game::newGame() { + mPlayer = Character(); + mPlayer.setName(QStringLiteral("Hero")); + mPlayer.setClassType(Character::Archer); + mPlayer.setLevel(15); + + mLevels.clear(); + + Level village; + QList<Character> villageNpcs; + villageNpcs.append(Character(QStringLiteral("Barry the Blacksmith"), 10, Character::Warrior)); + villageNpcs.append(Character(QStringLiteral("Terry the Trader"), 10, Character::Warrior)); + village.setNpcs(villageNpcs); + mLevels.append(village); + + Level dungeon; + QList<Character> dungeonNpcs; + dungeonNpcs.append(Character(QStringLiteral("Eric the Evil"), 20, Character::Mage)); + dungeonNpcs.append(Character(QStringLiteral("Eric's Sidekick #1"), 5, Character::Warrior)); + dungeonNpcs.append(Character(QStringLiteral("Eric's Sidekick #2"), 5, Character::Warrior)); + dungeon.setNpcs(dungeonNpcs); + mLevels.append(dungeon); +} +//! [0] + +//! [3] +bool Game::loadGame(Game::SaveFormat saveFormat) +{ + QFile loadFile(saveFormat == Json + ? QStringLiteral("save.json") + : QStringLiteral("save.dat")); + + if (!loadFile.open(QIODevice::ReadOnly)) { + qWarning("Couldn't open save file."); + return false; + } + + QByteArray saveData = loadFile.readAll(); + + QJsonDocument loadDoc(saveFormat == Json + ? QJsonDocument::fromJson(saveData) + : QJsonDocument::fromBinaryData(saveData)); + + read(loadDoc.object()); + + return true; +} +//! [3] + +//! [4] +bool Game::saveGame(Game::SaveFormat saveFormat) const +{ + QFile saveFile(saveFormat == Json + ? QStringLiteral("save.json") + : QStringLiteral("save.dat")); + + if (!saveFile.open(QIODevice::WriteOnly)) { + qWarning("Couldn't open save file."); + return false; + } + + QJsonObject gameObject; + write(gameObject); + QJsonDocument saveDoc(gameObject); + saveFile.write(saveFormat == Json + ? saveDoc.toJson() + : saveDoc.toBinaryData()); + + return true; +} +//! [4] + +//! [1] +void Game::read(const QJsonObject &json) +{ + mPlayer.read(json["player"].toObject()); + + mLevels.clear(); + QJsonArray levelArray = json["levels"].toArray(); + for (int levelIndex = 0; levelIndex < levelArray.size(); ++levelIndex) { + QJsonObject levelObject = levelArray[levelIndex].toObject(); + Level level; + level.read(levelObject); + mLevels.append(level); + } +} +//! [1] + +//! [2] +void Game::write(QJsonObject &json) const +{ + QJsonObject playerObject; + mPlayer.write(playerObject); + json["player"] = playerObject; + + QJsonArray levelArray; + foreach (const Level level, mLevels) { + QJsonObject levelObject; + level.write(levelObject); + levelArray.append(levelObject); + } + json["levels"] = levelArray; +} +//! [2] diff --git a/examples/widgets/tutorials/addressbook-fr/part6/finddialog.h b/examples/json/savegame/game.h index 42ff91143e..9216a373d1 100644 --- a/examples/widgets/tutorials/addressbook-fr/part6/finddialog.h +++ b/examples/json/savegame/game.h @@ -38,31 +38,38 @@ ** ****************************************************************************/ -#ifndef FINDDIALOG_H -#define FINDDIALOG_H +#ifndef GAME_H +#define GAME_H -#include <QDialog> +#include <QJsonObject> +#include <QList> -QT_BEGIN_NAMESPACE -class QLineEdit; -class QPushButton; -QT_END_NAMESPACE +#include "character.h" +#include "level.h" -class FindDialog : public QDialog +//! [0] +class Game { - Q_OBJECT - public: - FindDialog(QWidget *parent = 0); - QString getFindText(); + Game(); + + enum SaveFormat { + Json, Binary + }; + + const Character &player() const; + const QList<Level> &levels() const; -public slots: - void findClicked(); + void newGame(); + bool loadGame(SaveFormat saveFormat); + bool saveGame(SaveFormat saveFormat) const; + void read(const QJsonObject &json); + void write(QJsonObject &json) const; private: - QPushButton *findButton; - QLineEdit *lineEdit; - QString findText; + Character mPlayer; + QList<Level> mLevels; }; +//! [0] -#endif +#endif // GAME_H diff --git a/examples/widgets/tutorials/addressbook-fr/part2/addressbook.h b/examples/json/savegame/level.cpp index b126432860..afbd3e0fa0 100644 --- a/examples/widgets/tutorials/addressbook-fr/part2/addressbook.h +++ b/examples/json/savegame/level.cpp @@ -38,47 +38,46 @@ ** ****************************************************************************/ -#ifndef ADDRESSBOOK_H -#define ADDRESSBOOK_H +#include "level.h" -#include <QWidget> -#include <QMap> +#include <QJsonArray> -QT_BEGIN_NAMESPACE -class QLabel; -class QLineEdit; -class QPushButton; -class QTextEdit; -QT_END_NAMESPACE +Level::Level() { +} -class AddressBook : public QWidget +const QList<Character> &Level::npcs() const { - Q_OBJECT + return mNpcs; +} -public: - AddressBook(QWidget *parent = 0); - -//! [slots] -public slots: - void addContact(); - void submitContact(); - void cancel(); -//! [slots] - -//! [pushbutton declaration] -private: - QPushButton *addButton; - QPushButton *submitButton; - QPushButton *cancelButton; - QLineEdit *nameLine; - QTextEdit *addressText; -//! [pushbutton declaration] +void Level::setNpcs(const QList<Character> &npcs) +{ + mNpcs = npcs; +} -//! [remaining private variables] - QMap<QString, QString> contacts; - QString oldName; - QString oldAddress; -}; -//! [remaining private variables] +//! [0] +void Level::read(const QJsonObject &json) +{ + mNpcs.clear(); + QJsonArray npcArray = json["npcs"].toArray(); + for (int npcIndex = 0; npcIndex < npcArray.size(); ++npcIndex) { + QJsonObject npcObject = npcArray[npcIndex].toObject(); + Character npc; + npc.read(npcObject); + mNpcs.append(npc); + } +} +//! [0] -#endif +//! [1] +void Level::write(QJsonObject &json) const +{ + QJsonArray npcArray; + foreach (const Character npc, mNpcs) { + QJsonObject npcObject; + npc.write(npcObject); + npcArray.append(npcObject); + } + json["npcs"] = npcArray; +} +//! [1] diff --git a/examples/widgets/tutorials/addressbook-fr/part1/addressbook.h b/examples/json/savegame/level.h index 01dbf547e1..6cdf508c87 100644 --- a/examples/widgets/tutorials/addressbook-fr/part1/addressbook.h +++ b/examples/json/savegame/level.h @@ -38,29 +38,28 @@ ** ****************************************************************************/ -#ifndef ADDRESSBOOK_H -#define ADDRESSBOOK_H +#ifndef LEVEL_H +#define LEVEL_H -#include <QWidget> +#include <QJsonObject> +#include <QList> -QT_BEGIN_NAMESPACE -class QLabel; -class QLineEdit; -class QTextEdit; -QT_END_NAMESPACE +#include "character.h" -//! [class definition] -class AddressBook : public QWidget +//! [0] +class Level { - Q_OBJECT - public: - AddressBook(QWidget *parent = 0); + Level(); + + const QList<Character> &npcs() const; + void setNpcs(const QList<Character> &npcs); + void read(const QJsonObject &json); + void write(QJsonObject &json) const; private: - QLineEdit *nameLine; - QTextEdit *addressText; + QList<Character> mNpcs; }; -//! [class definition] +//! [0] -#endif +#endif // LEVEL_H diff --git a/examples/widgets/tutorials/addressbook-fr/part4/main.cpp b/examples/json/savegame/main.cpp index 70eabab255..1b44306bb0 100644 --- a/examples/widgets/tutorials/addressbook-fr/part4/main.cpp +++ b/examples/json/savegame/main.cpp @@ -38,15 +38,33 @@ ** ****************************************************************************/ -#include <QtWidgets> -#include "addressbook.h" +#include <QCoreApplication> +#include "game.h" +//! [0] int main(int argc, char *argv[]) { - QApplication app(argc, argv); + QCoreApplication app(argc, argv); - AddressBook addressBook; - addressBook.show(); + Game game; + game.newGame(); + // Game is played; changes are made... +//! [0] +//! [1] + if (!game.saveGame(Game::Json)) + return 1; - return app.exec(); + if (!game.saveGame(Game::Binary)) + return 1; + + Game fromJsonGame; + if (!fromJsonGame.loadGame(Game::Json)) + return 1; + + Game fromBinaryGame; + if (!fromBinaryGame.loadGame(Game::Binary)) + return 1; + + return 0; } +//! [1] diff --git a/examples/json/savegame/savegame.pro b/examples/json/savegame/savegame.pro new file mode 100644 index 0000000000..fd754ace80 --- /dev/null +++ b/examples/json/savegame/savegame.pro @@ -0,0 +1,22 @@ +QT += core +QT -= gui + +TARGET = savegame +CONFIG += console +CONFIG -= app_bundle + +TEMPLATE = app + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/json/savegame +INSTALLS += target + +SOURCES += main.cpp \ + character.cpp \ + game.cpp \ + level.cpp + +HEADERS += \ + character.h \ + game.h \ + level.h diff --git a/examples/widgets/doc/src/addressbook-fr.qdoc b/examples/widgets/doc/src/addressbook-fr.qdoc deleted file mode 100644 index 7d15d99597..0000000000 --- a/examples/widgets/doc/src/addressbook-fr.qdoc +++ /dev/null @@ -1,1019 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia. For licensing terms and -** conditions see http://qt.digia.com/licensing. For further information -** use the contact form at http://qt.digia.com/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$ -** -****************************************************************************/ - -/*! - \page tutorials-addressbook-fr.html - - \title Tutoriel "Carnet d'adresses" - \brief Une introduction à la programation d'interface graphique montrant comment construire une application simple avec Qt. - - Ce tutoriel est une introduction à la programmation de GUI (interface utilisateur) - à l'aide des outils fournis par la plateforme multiplate-forme Qt. - - \image addressbook-tutorial-screenshot.png - - Ce tutoriel va nous amener à découvrir quelques technologies fondamentales fournies - par Qt, tel que: - - \list - \li Les Widgets et leur mise en page à l'aide des layouts - \li Les signaux et slots - \li Les structures de données de collections - \li Les entrées/sorties - \endlist - - Le code source du tutoriel est distribué avec Qt dans le dossier \c tutorials/addressbook - - Les chapitres du tutoriel: - - \list 1 - \li \l{tutorials/addressbook-fr/part1}{Conception de l'interface utilisateur} - \li \l{tutorials/addressbook-fr/part2}{Ajouter des adresses} - \li \l{tutorials/addressbook-fr/part3}{Navigation entre les éléments} - \li \l{tutorials/addressbook-fr/part4}{éditer et supprimer des adresses} - \li \l{tutorials/addressbook-fr/part5}{Ajout d'une fonction de recherche} - \li \l{tutorials/addressbook-fr/part6}{Sauvegarde et chargement} - \li \l{tutorials/addressbook-fr/part7}{Fonctionnalités avancées} - \endlist - - La petite application que nous développerons ici ne possède pas tous les éléments - des interfaces dernier cri, elle va nous permettre d'utiliser les techniques de base - utilisées dans les applications plus complexes. - - Lorsque vous aurez terminé ce tutoriel, nous vous recommandons de poursuivre avec l'exemple - "\l{mainwindows/application}{Application}", qui présente une interface simple utilisant - les menus et barres d'outils, la barre d'état, etc. - -*/ - -/*! - \example tutorials/addressbook-fr/part1 - \title Carnet d'adresses 1 - Conception de l'interface utilisateur - - La première partie de ce tutoriel traite de la conception d'une interface graphique - (GUI) basique, que l'on utilisera pour l'application Carnet d'adresses. - - La première étape dans la création d'applications graphiques est la conception de - l'interface utilisateur. Dans ce chapitre, nous verrons comment créer les labels - et champs de saisie nécessaires à l'implementation d'un carnet d'adresses de base. - Le résultat attendu est illustré par la capture d'écran ci-dessous. - - \image addressbook-tutorial-part1-screenshot.png - - Nous allons avoir besoin de deux objets QLabel, \c nameLabel et \c addressLabel, - ainsi que deux champs de saisie: un objet QLineEdit, \c nameLine, et un objet - QTextEdit, \c addressText, afin de permettre à l'utilisateur d'entrer le nom d'un - contact et son adresse. Les widgets utilisés ainsi que leur placement sont visibles ci-dessous. - - \image addressbook-tutorial-part1-labeled-screenshot.png - - Trois fichiers sont nécessaires à l'implémentation de ce carnet d'adresses: - - \list - \li \c{addressbook.h} - le fichier de définition (header) pour la classe \c AddressBook, - \li \c{addressbook.cpp} - le fichier source, qui comprend l'implémentation de la classe - \c AddressBook - \li \c{main.cpp} - le fichier qui contient la méthode \c main() , et - une instance de la classe \c AddressBook. - \endlist - - \section1 Programmation en Qt - héritage - - - Lorsque l'on écrit des programmes avec Qt, on a généralement recours à - l'héritage depuis des objets Qt, afin d'y ajouter des fonctionnalités. - C'est l'un des concepts fondamentaux de la création de widgets personnalisés - ou de collections de widgets. Utiliser l'héritage afin de compléter - ou modifier le comportement d'un widget présente les avantages suivants: - - \list - \li La possibilité d'implémenter des méthodes virtuelles et des méthodes - virtuelles pures pour obtenir exactement ce que l'on souhaite, avec la possibilité - d'utiliser l'implémentation de la classe mère si besoin est. - \li Cela permet l'encapsulation partielle de l'interface utilisateur dans une classe, - afin que les autres parties de l'application n'aient pas à se soucier de chacun des - widgets qui forment l'interface utilisateur. - \li La classe fille peut être utilisée pour créer de nombreux widgets personnalisés - dans une même application ou bibliothèque, et le code de la classe fille peut être - réutilisé dans d'autres projets - \endlist - - Comme Qt ne fournit pas de widget standard pour un carnet d'adresses, nous - partirons d'une classe de widget Qt standard et y ajouterons des fonctionnalités. - La classe \c AddressBook crée dans ce tutoriel peut être réutilisée si on a besoin d'un - widget carnet d'adresses basique. - - - \section1 La classe AddressBook - - Le fichier \l{tutorials/addressbook-fr/part1/addressbook.h}{\c addressbook.h} permet de - définir la classe \c AddressBook. - - On commence par définir \c AddressBook comme une classe fille de QWidget et déclarer - un constructeur. On utilise également la macro Q_OBJECT pour indiquer que la classe - exploite les fonctionnalités de signaux et slots offertes par Qt ainsi que - l'internationalisation, bien que nous ne les utilisions pas à ce stade. - - \snippet tutorials/addressbook-fr/part1/addressbook.h class definition - - La classe contient les déclarations de \c nameLine et \c addressText, - les instances privées de QLineEdit et QTextEdit mentionnées précédemment. - Vous verrez, dans les chapitres à venir que les informations contenues - dans \c nameLine et \c addressText sont nécessaires à de nombreuses méthodes - du carnet d'adresses. - - Il n'est pas nécessaire de déclarer les objets QLabel que nous allons utiliser - puisque nous n'aurons pas besoin d'y faire référence après leur création. - La façon dont Qt gère la parenté des objets est traitée dans la section suivante. - - La macro Q_OBJECT implémente des fonctionnalités parmi les plus avancées de Qt. - Pour le moment, il est bon de voir la macro Q_OBJECT comme un raccourci nous - permettant d'utiliser les méthodes \l{QObject::}{tr()} et \l{QObject::}{connect()}. - - Nous en avons maintenant terminé avec le fichier \c addressbook.h et allons - passer à l'implémentation du fichier \c addressbook.cpp. - - \section1 Implémentation de la classe AddressBook - - Le constructeur de la classe \c{AddressBook} prend en paramètre un QWidget, \e parent. - Par convention, on passe ce paramètre au constructeur de la classe mère. - Ce concept de parenté, où un parent peut avoir un ou plusieurs enfants, est utile - pour regrouper les Widgets avec Qt. Par exemple, si vous détruisez le parent, - tous ses enfants seront détruits égalament. - - - \snippet tutorials/addressbook/part1/addressbook.cpp constructor and input fields - - à l'intérieur de ce constructeur, on déclare et instancie deux objets locaux - QLabel, \c nameLabel et \c addressLabel, de même on instancie \c nameLine et - \c addressText. La méthode \l{QObject::tr()}{tr()} renvoie une version traduite - de la chaîne de caractères, si elle existe; dans le cas contraire, elle renvoie - la chaîne elle même. On peut voir cette méthode comme un marqueur \tt{<insérer - la traduction ici>}, permettant de repérer les objets QString à considérer - pour traduire une application. Vous remarquerez, dans les chapitres à venir - comme dans les exemples Qt, qu'elle est utilisée chaque fois - que l'on utilise une chaîne susceptible d'être traduite. - - Lorsque l'on programme avec Qt, il est utile de savoir comment fonctionnent les - agencements ou layouts. Qt fournit trois classes principales de layouts pour - contrôler le placement des widgets: QHBoxLayout, QVBoxLayout et QGridLayout. - - \image addressbook-tutorial-part1-labeled-layout.png - - On utilise un QGridLayout pour positionner nos labels et champs de saisie de manière - structurée. QGridLayout divise l'espace disponible en une grille, et place les - widgets dans les cellules que l'on spécifie par les numéros de ligne et de colonne. - Le diagramme ci-dessus présente les cellules et la position des widgets, et cette - organisation est obtenue à l'aide du code suivant: - - \snippet tutorials/addressbook/part1/addressbook.cpp layout - - On remarque que le label \c AddressLabel est positionné en utilisant Qt::AlignTop - comme argument optionnel. Ceci est destiné à assurer qu'il ne sera pas centré - verticalement dans la cellule (1,0). Pour un aperçu rapide des layouts de Qt, - consultez la section \l{Layout Management}. - - Afin d'installer l'objet layout dans un widget, il faut appeler la méthode - \l{QWidget::setLayout()}{setLayout()} du widget en question: - - \snippet tutorials/addressbook/part1/addressbook.cpp setting the layout - - Enfin, on initialise le titre du widget à "Simple Address Book" - - \section1 Exécution de l'application - - Un fichier séparé, \c main.cpp, est utilisé pour la méthode \c main(). Dans cette - fonction, on crée une instance de QApplication, \c app. QApplication se charge de - des ressources communes à l'ensemble de l'application, tel que les polices de - caractères et le curseur par défaut, ainsi que de l'exécution de la boucle d'évènements. - De ce fait, il y a toujours un objet QApplication dans toute application graphique en Qt. - - \snippet tutorials/addressbook/part1/main.cpp main function - - On construit un nouveau widget \c AddressBook sur la pile et on invoque - sa méthode \l{QWidget::show()}{show()} pour l'afficher. - Cependant, le widget ne sera pas visible tant que la boucle d'évènements - n'aura pas été lancée. On démarre la boucle d'évènements en appelant la - méthode \l{QApplication::}{exec()} de l'application; le résultat renvoyé - par cette méthode est lui même utilisé comme valeur de retour pour la méthode - \c main(). - On comprend maintenant pourquoi \c AddressBook a été créé sur la pile: à la fin - du programme, l'objet sort du scope de la fonction \c main() et tous ses widgets enfants - sont supprimés, assurant ainsi qu'il n'y aura pas de fuites de mémoire. -*/ - -/*! - \example tutorials/addressbook-fr/part2 - \title Carnet d'adresses 2 - Ajouter des adresses - - La prochaine étape pour créer notre carnet d'adresses est d'ajouter un soupçon - d'interactivité. - - \image addressbook-tutorial-part2-add-contact.png - - Nous allons fournir un bouton que l'utilisateur peut - cliquer pour ajouter un nouveau contact. Une structure de données est aussi - nécessaire afin de pouvoir stocker les contacts en mémoire. - - \section1 Définition de la classe AddressBook - - Maintenant que nous avons mis en place les labels et les champs de saisie, - nous ajoutons les boutons pour compléter le processus d'ajout d'un contact. - Cela veut dire que notre fichier \c addressbook.h a maintenant trois - objets QPushButton et trois slots publics correspondant. - - \snippet tutorials/addressbook/part2/addressbook.h slots - - Un slot est une méthode qui répond à un signal. Nous allons - voir ce concept en détail lorsque nous implémenterons la classe \c{AddressBook}. - Pour une explication détaillée du concept de signal et slot, vous pouvez - vous référer au document \l{Signals and Slots}. - - Les trois objets QPushButton \c addButton, \c submitButton et \c cancelButton - sont maintenant inclus dans la déclaration des variables privées, avec - \c nameLine et \c addressText du chapitre précédent. - - \snippet tutorials/addressbook/part2/addressbook.h pushbutton declaration - - Nous avons besoin d'un conteneur pour stocker les contacts du carnet - d'adresses, de façon à pouvoir les énumérer et les afficher. - Un objet QMap, \c contacts, est utilisé pour ça, car il permet de stocker - des paires clé-valeur: le nom du contact est la \e{clé} et l'adresse du contact - est la \e{valeur}. - - \snippet tutorials/addressbook/part2/addressbook.h remaining private variables - - Nous déclarons aussi deux objects QString privés: \c oldName et \c oldAddress. - Ces objets sont nécessaires pour conserver le nom et l'adresse du dernier contact - affiché avant que l'utilisateur ne clique sur le bouton "Add". Grâce à ces variables - si l'utilisateur clique sur "Cancel", il est possible de revenir - à l'affichage du dernier contact. - - \section1 Implémentation de la classe AddressBook - - Dans le constructeur de \c AddressBook, \c nameLine et - \c addressText sont mis en mode lecture seule, de façon à autoriser l'affichage - mais pas la modification du contact courant. - - \dots - \snippet tutorials/addressbook/part2/addressbook.cpp setting readonly 1 - \dots - \snippet tutorials/addressbook/part2/addressbook.cpp setting readonly 2 - - Ensuite, nous instancions les boutons \c addButton, \c submitButton, et - \c cancelButton. - - \snippet tutorials/addressbook/part2/addressbook.cpp pushbutton declaration - - Le bouton \c addButton est affiché en invoquant la méthode \l{QPushButton::show()} - {show()}, tandis que \c submitButton et \c cancelButton sont cachés en invoquant - \l{QPushButton::hide()}{hide()}. Ces deux boutons ne seront affichés que lorsque - l'utilisateur cliquera sur "Add", et ceci est géré par la méthode \c addContact() - décrite plus loin. - - \snippet tutorials/addressbook/part2/addressbook.cpp connecting signals and slots - - Nous connectons le signal \l{QPushButton::clicked()}{clicked()} de chaque bouton - au slot qui gèrera l'action. - L'image ci-dessous illustre ceci: - - \image addressbook-tutorial-part2-signals-and-slots.png - - Ensuite, nous arrangeons proprement les boutons sur la droite du widget - AddressBook, et nous utilisons un QVBoxLayout pour les aligner verticalement. - - \snippet tutorials/addressbook/part2/addressbook.cpp vertical layout - - La methode \l{QBoxLayout::addStretch()}{addStretch()} est utilisée pour - assurer que les boutons ne sont pas répartis uniformément, mais regroupés - dans la partie supperieure du widget. La figure ci-dessous montre la différence - si \l{QBoxLayout::addStretch()}{addStretch()} est utilisé ou pas. - - \image addressbook-tutorial-part2-stretch-effects.png - - Ensuite nous ajoutons \c buttonLayout1 à \c mainLayout, en utilisant - \l{QGridLayout::addLayout()}{addLayout()}. Ceci nous permet d'imbriquer les - mises en page puisque \c buttonLayout1 est maintenant un enfant de \c mainLayout. - - \snippet tutorials/addressbook/part2/addressbook.cpp grid layout - - Les coordonnées du layout global ressemblent maintenant à ça: - - \image addressbook-tutorial-part2-labeled-layout.png - - Dans la méthode \c addContact(), nous stockons les détails du dernier - contact affiché dans \c oldName et \c oldAddress. Ensuite, nous - vidons ces champs de saisie et nous désactivons le mode - lecture seule. Le focus est placé sur \c nameLine et on affiche - \c submitButton et \c cancelButton. - - \snippet tutorials/addressbook/part2/addressbook.cpp addContact - - La méthode \c submitContact() peut être divisée en trois parties: - - \list 1 - \li Nous extrayons les détails du contact depuis \c nameLine et \c addressText - et les stockons dans des objets QString. Nous les validons pour s'assurer - que l'utilisateur n'a pas cliqué sur "Add" avec des champs de saisie - vides; sinon un message est affiché avec QMessageBox pour rappeller à - l'utilisateur que les deux champs doivent être complétés. - - \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part1 - - \li Ensuite, nous vérifions si le contact existe déjà. Si aucun contacts - existant n'entre en conflit avec le nouveau, nous l'ajoutons à - \c contacts et nous affichons un QMessageBox pour informer l'utilisateur - que le contact a été ajouté. - - \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part2 - - Si le contact existe déjà, nous affichons un QMessageBox pour informer - l'utilisateur du problème. - Notre objet \c contacts est basé sur des paires clé-valeur formés par - le nom et l'adresse, nous voulons nous assurer que la \e clé est unique. - - \li Une fois que les deux vérifications précédentes ont été traitées, - nous restaurons les boutons à leur état normal à l'aide du code - suivant: - - \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part3 - - \endlist - - La capture d'écran ci-dessous montre l'affichage fournit par un objet - QMessageBox, utilisé ici pour afficher un message d'information - à l'utilisateur: - - \image addressbook-tutorial-part2-add-successful.png - - La méthode \c cancel() restaure les détails du dernier contact, active - \c addButton, et cache \c submitButton et \c cancelButton. - - \snippet tutorials/addressbook/part2/addressbook.cpp cancel - - L'idée générale pour augmenter la flexibilité lors de l'ajout d'un - contact est de donner la possiblité de cliquer sur "Add" - ou "Cancel" à n'importe quel moment. - L'organigramme ci-dessous reprend l'ensemble des interactions dévelopées - jusqu'ici: - - \image addressbook-tutorial-part2-add-flowchart.png -*/ - -/*! - \example tutorials/addressbook-fr/part3 - \title Carnet d'adresses 3 - Navigation entre les éléments - - L'application "Carnet d'adresses" est maintenant à moitié terminée. Il - nous faut maintenant ajouter quelques fonctions pour naviguer entre - les contacts. Avant de commencer, il faut se décider sur le type de structure de - données le plus approprié pour stocker les contacts. - - Dans le chapitre 2, nous avons utilisé un QMap utilisant des paires clé-valeur, - avec le nom du contact comme \e clé, et l'adresse du contact comme \e valeur. - Cela fonctionnait bien jusqu'ici, mais pour ajouter la navigation entre les - entrées, quelques améliorations sont nécessaires. - - Nous améliorerons le QMap en le faisant ressembler à une structure de données - similaire à une liste liée, où tous les éléments sont connectés, y compris - le premier et le dernier élément. La figure ci-dessous illustre cette structure - de donnée. - - \image addressbook-tutorial-part3-linkedlist.png - - \section1 Définition de la classe AddressBook - - Pour ajouter les fonctions de navigation au carnet d'adresses, nous avons - besoin de deux slots supplémentaires dans notre classe \c AddressBook: - \c next() et \c previous(). Ceux-ci sont ajoutés au fichier addressbook.h: - - \snippet tutorials/addressbook/part3/addressbook.h navigation functions - - Nous avons aussi besoin de deux nouveaux objets QPushButton, nous ajoutons - donc les variables privées \c nextButton et \c previousButton. - - \snippet tutorials/addressbook/part3/addressbook.h navigation pushbuttons - - \section1 Implémentation de la classe AddressBook - - A l'intérieur du constructeur de \c AddressBook, dans \c addressbook.cpp, nous - instancions \c nextButton et \c previousButton et nous les désactivons - par défaut. Nous faisons ceci car la navigation ne doit être activée - que lorsqu'il y a plus d'un contact dans le carnet d'adresses. - - \snippet tutorials/addressbook/part3/addressbook.cpp navigation pushbuttons - - Nous connectons alors ces boutons à leur slots respectifs: - - \snippet tutorials/addressbook/part3/addressbook.cpp connecting navigation signals - - L'image ci-dessous montre l'interface utilisateur que nous allons créer. - Remarquez que cela ressemble de plus en plus à l'interface du programme - complet. - - \image addressbook-tutorial-part3-screenshot.png - - Nous suivons les conventions pour les fonctions \c next() et \c previous() - en plaçant \c nextButton à droite et \c previousButton à gauche. Pour - faire cette mise en page intuitive, nous utilisons un QHBoxLayout pour - placer les widgets côte à côte: - - \snippet tutorials/addressbook/part3/addressbook.cpp navigation layout - - L'objet QHBoxLayout, \c buttonLayout2, est ensuite ajouté à \c mainLayout. - - \snippet tutorials/addressbook/part3/addressbook.cpp adding navigation layout - - La figure ci-dessous montre les systèmes de coordonnées pour les widgets du - \c mainLayout. - \image addressbook-tutorial-part3-labeled-layout.png - - Dans notre méthode \c addContact(), nous avons desactivé ces boutons - pour être sûr que l'utilisateur n'utilise pas la navigation lors de - l'ajout d'un contact. - - \snippet tutorials/addressbook/part3/addressbook.cpp disabling navigation - - Dans notre méthode \c submitContact(), nous activons les boutons de - navigation, \c nextButton et \c previousButton, en fonction de la - taille de \c contacts. Commen mentionné plus tôt, la navigation n'est - activée que si il y a plus d'un contact dans le carnet d'adresses. - Les lignes suivantes montrent comment faire cela: - - \snippet tutorials/addressbook/part3/addressbook.cpp enabling navigation - - Nous incluons aussi ces lignes de code dans le bouton \c cancel(). - - Souvenez vous que nous voulons émuler une liste-liée ciruculaire à - l'aide de l'objet QMap, \c contacts. Pour faire cela, nous obtenons un itérateur - sur \c contact dans la méthode \c next(), et ensuite: - - \list - \li Si l'itérateur n'est pas à la fin de \c contacts, nous l'incrémentons - \li Si l'itérateur est à la fin de \c contacts, nous changeons sa position - jusqu'au début de \c contacts. Cela donne l'illusion que notre QMap - fonctionne comme une liste circulaire. - \endlist - - \snippet tutorials/addressbook/part3/addressbook.cpp next() function - - Une fois que nous avons itéré jusqu'à l'objet recherché dans \c contacts, - nous affichons son contenu sur \c nameLine et \c addressText. - - De la même façon, pour la méthode \c previous(), nous obtenons un - itérateur sur \c contacts et ensuite: - - \list - \li Si l'itérateur est à la fin de \c contacts, on réinitialise - l'affichage et on retourne. - \li Si l'itérateur est au début de \c contacts, on change sa - position jusqu'à la fin - \li Ensuite, on décrémente l'itérateur - \endlist - - \snippet tutorials/addressbook/part3/addressbook.cpp previous() function - - à nouveau, nous affichons le contenu de l'objet courant dans \c contacts. - -*/ - -/*! - - \example tutorials/addressbook-fr/part4 - \title Carnet d'Adresses 4 - éditer et supprimer des adresses - - - Dans ce chapitre, nous verrons comment modifier les données des contacts - contenus dans l'application carnet d'adresses. - - - \image addressbook-tutorial-screenshot.png - - Nous avons maintenant un carnet d'adresses qui ne se contente pas de - lister des contacts de façon ordonnée, mais permet également la - navigation. Il serait pratique d'inclure des fonctions telles qu'éditer et - supprimer, afin que les détails associés à un contact puissent être - modifiés lorsque c'est nécessaire. Cependant, cela requiert une légère - modification, sous la forme d'énumérations. Au chapitre précédent, nous avions deux - modes: \c {AddingMode} et \c {NavigationMode}, mais ils n'étaient pas - définis en tant qu'énumérations. Au lieu de ça, on activait et désactivait les - boutons correspondants manuellement, au prix de multiples redondances dans - le code. - - Dans ce chapitre, on définit l'énumération \c Mode avec trois valeurs possibles. - - \list - \li \c{NavigationMode}, - \li \c{AddingMode}, et - \li \c{EditingMode}. - \endlist - - \section1 Définition de la classe AddressBook - - Le fichier \c addressbook.h est mis a jour pour contenir l'énumération \c Mode : - - \snippet tutorials/addressbook/part4/addressbook.h Mode enum - - On ajoute également deux nouveaux slots, \c editContact() et - \c removeContact(), à notre liste de slots publics. - - \snippet tutorials/addressbook/part4/addressbook.h edit and remove slots - - Afin de basculer d'un mode à l'autre, on introduit la méthode - \c updateInterface() pour contrôller l'activation et la désactivation de - tous les objets QPushButton. On ajoute également deux nouveaux boutons, - \c editButton et \c removeButton, pour les fonctions d'édition - et de suppression mentionnées plus haut. - - \snippet tutorials/addressbook/part4/addressbook.h updateInterface() declaration - \dots - \snippet tutorials/addressbook/part4/addressbook.h buttons declaration - \dots - \snippet tutorials/addressbook/part4/addressbook.h mode declaration - - Enfin, on déclare \c currentMode pour garder une trace du mode - actuellement utilisé. - - \section1 Implémentation de la classe AddressBook - - Il nous faut maintenant implémenter les fonctionnalités de changement de - mode de l'application carnet d'adresses. Les boutons \c editButton et - \c removeButton sont instanciés et désactivés par défaut, puisque le - carnet d'adresses démarre sans aucun contact en mémoire. - - \snippet tutorials/addressbook/part4/addressbook.cpp edit and remove buttons - - Ces boutons sont ensuite connectés à leurs slots respectifs, - \c editContact() et \c removeContact(), avant d'être ajoutés à - \c buttonLayout1. - - \snippet tutorials/addressbook/part4/addressbook.cpp connecting edit and remove - \dots - \snippet tutorials/addressbook/part4/addressbook.cpp adding edit and remove to the layout - - La methode \c editContact() place les anciens détails du contact dans - \c oldName et \c oldAddress, avant de basculer vers le mode - \c EditingMode. Dans ce mode, les boutons \c submitButton et - \c cancelButton sont tous deux activés, l'utilisateur peut par conséquent - modifier les détails du contact et cliquer sur l'un de ces deux boutons - par la suite. - - \snippet tutorials/addressbook/part4/addressbook.cpp editContact() function - - La méthode \c submitContact() a été divisée en deux avec un bloc - \c{if-else}. On teste \c currentMode pour voir si le mode courant est - \c AddingMode. Si c'est le cas, on procède à l'ajout. - - \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function beginning - \dots - \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function part1 - - Sinon, on s'assure que \c currentMode est en \c EditingMode. Si c'est le - cas, on compare \c oldName et \c name. Si le nom a changé, on supprime - l'ancien contact de \c contacts et on insère le contact mis a jour. - - \snippet tutorials/addressbook/part4/addressbook.cpp submitContact() function part2 - - Si seule l'adresse a changé (i.e. \c oldAddress n'est pas identique à - \c address), on met à jour l'adresse du contact. Enfin on règle - \c currentMode à \c NavigationMode. C'est une étape importante puisque - c'est cela qui réactive tous les boutons désactivés. - - Afin de retirer un contact du carnet d'adresses, on implémente la méthode - \c removeContact(). Cette méthode vérifie que le contact est présent dans - \c contacts. - - \snippet tutorials/addressbook/part4/addressbook.cpp removeContact() function - - Si c'est le cas, on affiche une boîte de dialogue QMessageBox, demandant - confirmation de la suppression à l'utilisateur. Une fois la confirmation - effectuée, on appelle \c previous(), afin de s'assurer que l'interface - utilisateur affiche une autre entrée, et on supprime le contact en - utilisant le méthode \l{QMap::remove()}{remove()} de \l{QMap}. Dans un - souci pratique, on informe l'utilisateur de la suppression par le biais - d'une autre QMessageBox. Les deux boîtes de dialogue utilisées dans cette - méthode sont représentées ci-dessous. - - \image addressbook-tutorial-part4-remove.png - - \section2 Mise à jour de l'Interface utilisateur - - On a évoqué plus haut la méthode \c updateInterface() comme moyen - d'activer et de désactiver les différents boutons de l'interface en - fonction du mode. Cette méthode met à jour le mode courant selon - l'argument \c mode qui lui est passé, en l'assignant à \c currentMode, - avant de tester sa valeur. - - Chacun des boutons est ensuite activé ou désactivé, en fonction du mode. - Le code source pour les cas \c AddingMode et \c EditingMode est visible - ci-dessous: - - \snippet tutorials/addressbook/part4/addressbook.cpp update interface() part 1 - - Dans le cas de \c NavigationMode, en revanche, des tests conditionnels - sont passés en paramètre de QPushButton::setEnabled(). Ceci permet de - s'assurer que les boutons \c editButton et \c removeButton ne sont activés - que s'il existe au moins un contact dans le carnet d'adresses; - \c nextButton et \c previousButton ne sont activés que lorsqu'il existe - plus d'un contact dans le carnet d'adresses. - - \snippet tutorials/addressbook/part4/addressbook.cpp update interface() part 2 - - En effectuant les opérations de réglage du mode et de mise à jour de - l'interface utilisateur au sein de la même méthode, on est à l'abri de - l'éventualité où l'interface utilisateur se "désynchronise" de l'état - interne de l'application. - -*/ - -/*! - \example tutorials/addressbook-fr/part5 - \title Carnet d'adresse 5 - Ajout d'une fonction de recherche - - Dans ce chapitre, nous allons voir les possibilités pour rechercher - des contacts dans le carnet d'adresse. - - \image addressbook-tutorial-part5-screenshot.png - - Plus nous ajoutons des contacts dans l'application, plus - il devient difficile de naviguer avec les boutons \e Next et \e Previous. - Dans ce cas, une fonction de recherche serait plus efficace pour rechercher - les contacts. - La capture d'écran ci-dessus montre le bouton de recherche \e Find et sa position - dans le paneau de bouton. - - Lorsque l'utilisateur clique sur le bouton \e Find, il est courant d'afficher - une boîte de dialogue qui demande à l'utilisateur d'entrer un nom de contact. - Qt fournit la classe QDialog, que nous sous-classons dans ce chapitre pour - implémenter la class \c FindDialog. - - \section1 Définition de la classe FindDialog - - \image addressbook-tutorial-part5-finddialog.png - - Pour sous-classer QDialog, nous commençons par inclure le header de - QDialog dans le fichier \c finddialog.h. De plus, nous déclarons les - classes QLineEdit et QPushButton car nous utilisons ces widgets dans - notre classe dialogue. - - Tout comme dans la classe \c AddressBook, la classe \c FindDialog utilise - la macro Q_OBJECT et son constructeur est défini de façon à accepter - un QWidget parent, même si cette boîte de dialogue sera affichée dans une - fenêtre séparée. - - \snippet tutorials/addressbook/part5/finddialog.h FindDialog header - - Nous définissons la méthode publique \c getFindText() pour être utilisée - par les classes qui instancient \c FindDialog, ce qui leur permet d'obtenir - le texte entré par l'utilisateur. Un slot public, \c findClicked(), est - défini pour prendre en charge le texte lorsque l'utilisateur clique sur - le bouton \uicontrol Find. - - Finalement, nous définissons les variables privées \c findButton, - \c lineEdit et \c findText, qui correspondent respectivement au bouton - \uicontrol Find, au champ de texte dans lequel l'utilisateur tape le texte - à rechercher, et à une variable interne stockant le texte pour une - utilisation ultérieure. - - \section1 Implémentation de la classe FindDialog - - Dans le constructeur de \c FindDialog, nous instancions les objets des - variables privées \c lineEdit, \c findButton et \c findText. Nous utilisons ensuite - un QHBoxLayout pour positionner les widgets. - - \snippet tutorials/addressbook/part5/finddialog.cpp constructor - - Nous mettons en place la mise en page et le titre de la fenêtre, et - nous connectons les signaux aux slots. Remarquez que le signal - \l{QPushButton::clicked()}{clicked()} de \c{findButton} est connecté - à \c findClicked() et \l{QDialog::accept()}{accept()}. Le slot - \l{QDialog::accept()}{accept()} fourni par le QDialog ferme - la boîte de dialogue et lui donne le code de retour \l{QDialog::}{Accepted}. - Nous utilisons cette fonction pour aider la méthode \c findContact() de la classe - \c{AddressBook} à savoir si l'objet \c FindDialog a été fermé. Ceci sera - expliqué plus loin lorsque nous verrons la méthode \c findContact(). - - \image addressbook-tutorial-part5-signals-and-slots.png - - Dans \c findClicked(), nous validons le champ de texte pour nous - assurer que l'utilisateur n'a pas cliqué sur le bouton \uicontrol Find sans - avoir entré un nom de contact. Ensuite, nous stockons le texte du champ - d'entrée \c lineEdit dans \c findText. Et finalement nous vidons le - contenu de \c lineEdit et cachons la boîte de dialogue. - - \snippet tutorials/addressbook/part5/finddialog.cpp findClicked() function - - La variable \c findText a un accesseur publique associé: \c getFindText(). - Étant donné que nous ne modifions \c findText directement que dans le - constructeur et la méthode \c findClicked(), nous ne créons pas - de manipulateurs associé à \c getFindText(). - Puisque \c getFindText() est publique, les classes instanciant et - utilisant \c FindDialog peuvent toujours accéder à la chaîne de - caractères que l'utilisateur a entré et accepté. - - \snippet tutorials/addressbook/part5/finddialog.cpp getFindText() function - - \section1 Définition de la classe AddressBook - - Pour utiliser \c FindDialog depuis la classe \c AddressBook, nous - incluons \c finddialog.h dans le fichier \c addressbook.h. - - \snippet tutorials/addressbook/part5/addressbook.h include finddialog's header - - Jusqu'ici, toutes les fonctionnalités du carnet d'adresses ont un - QPushButton et un slot correspondant. De la même façon, pour la - fonctionnalité \uicontrol Find, nous avons \c findButton et \c findContact(). - - Le \c findButton est déclaré comme une variable privée et la - méthode \c findContact() est déclarée comme un slot public. - - \snippet tutorials/addressbook/part5/addressbook.h findContact() declaration - \dots - \snippet tutorials/addressbook/part5/addressbook.h findButton declaration - - Finalement, nous déclarons la variable privée \c dialog que nous allons - utiliser pour accéder à une instance de \c FindDialog. - - \snippet tutorials/addressbook/part5/addressbook.h FindDialog declaration - - Une fois que nous avons instancié la boîte de dialogue, nous voulons l'utiliser - plus qu'une fois. Utiliser une variable privée nous permet d'y référer - à plus d'un endroit dans la classe. - - \section1 Implémentation de la classe AddressBook - - Dans le constructeur de \c AddressBook, nous instancions nos objets privés, - \c findbutton et \c findDialog: - - \snippet tutorials/addressbook/part5/addressbook.cpp instantiating findButton - \dots - \snippet tutorials/addressbook/part5/addressbook.cpp instantiating FindDialog - - Ensuite, nous connectons le signal \l{QPushButton::clicked()}{clicked()} de - \c{findButton} à \c findContact(). - - \snippet tutorials/addressbook/part5/addressbook.cpp signals and slots for find - - Maintenant, tout ce qui manque est le code de notre méthode \c findContact(): - - \snippet tutorials/addressbook/part5/addressbook.cpp findContact() function - - Nous commençons par afficher l'instance de \c FindDialog, \c dialog. - L'utilisateur peut alors entrer le nom du contact à rechercher. Lorsque - l'utilisateur clique sur le bouton \c findButton, la boîte de dialogue est - masquée et le code de retour devient QDialog::Accepted. Ce code de retour - vient remplir la condition du premier if. - - Ensuite, nous extrayons le texte que nous utiliserons pour la recherche, - il s'agit ici de \c contactName obtenu à l'aide de la méthode \c getFindText() - de \c FindDialog. Si le contact existe dans le carnet d'adresse, nous - l'affichons directement. Sinon, nous affichons le QMessageBox suivant pour - indiquer que la recherche à échouée. - - \image addressbook-tutorial-part5-notfound.png -*/ - -/*! - \example tutorials/addressbook-fr/part6 - \title Carnet d'Adresses 6 - Sauvegarde et chargement - - Ce chapitre couvre les fonctionnalités de gestion des fichiers de Qt que - l'on utilise pour écrire les procédures de sauvegarde et chargement pour - l'application carnet d'adresses. - - \image addressbook-tutorial-part6-screenshot.png - - Bien que la navigation et la recherche de contacts soient des - fonctionnalités importantes, notre carnet d'adresses ne sera pleinement - utilisable qu'une fois que l'on pourra sauvegarder les contacts existants - et les charger à nouveau par la suite. - Qt fournit de nombreuses classes pour gérer les \l{Input/Output and - Networking}{entrées et sorties}, mais nous avons choisi de nous contenter d'une - combinaison de deux classes simples à utiliser ensemble: QFile et QDataStream. - - Un objet QFile représente un fichier sur le disque qui peut être lu, et - dans lequel on peut écrire. QFile est une classe fille de la classe plus - générique QIODevice, qui peut représenter différents types de - périphériques. - - Un objet QDataStream est utilisé pour sérialiser des données binaires - dans le but de les passer à un QIODevice pour les récupérer dans le - futur. Pour lire ou écrire dans un QIODevice, il suffit d'ouvrir le - flux, avec le périphérique approprié en paramètre, et d'y lire ou - écrire. - - \section1 Définition de la classe AddressBook - - On déclare deux slots publics, \c saveToFile() et \c loadFromFile(), - ainsi que deux objets QPushButton, \c loadButton et \c saveButton. - - \snippet tutorials/addressbook/part6/addressbook.h save and load functions declaration - \dots - \snippet tutorials/addressbook/part6/addressbook.h save and load buttons declaration - - \section1 Implémentation de la classe AddressBook - - Dans notre constructeur, on instancie \c loadButton et \c saveButton. - Idéalement, l'interface serait plus conviviale avec des boutons - affichant "Load contacts from a file" et "Save contacts to a file". Mais - compte tenu de la dimension des autres boutons, on initialise les labels - des boutons à \uicontrol{Load...} et \uicontrol{Save...}. Heureusement, Qt offre une - façon simple d'ajouter des info-bulles avec - \l{QWidget::setToolTip()}{setToolTip()}, et nous l'exploitons de la façon - suivante pour nos boutons: - - \snippet tutorials/addressbook/part6/addressbook.cpp tooltip 1 - \dots - \snippet tutorials/addressbook/part6/addressbook.cpp tooltip 2 - - Bien qu'on ne cite pas le code correspondant ici, nous ajoutons ces deux boutons au - layout de droite, \c button1Layout, comme pour les fonctionnalités précédentes, et - nous connectons leurs signaux - \l{QPushButton::clicked()}{clicked()} à leurs slots respectifs. - - Pour la sauvegarde, on commence par récupérer le nom de fichier - \c fileName, en utilisant QFileDialog::getSaveFileName(). C'est une - méthode pratique fournie par QFileDialog, qui ouvre une boîte de - dialogue modale et permet à l'utilisateur d'entrer un nom de fichier ou - de choisir un fichier \c{.abk} existant. Les fichiers \c{.abk} - correspondent à l'extension choisie pour la sauvegarde des contacts de - notre carnet d'adresses. - - \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part1 - - La boîte de dialogue affichée est visible sur la capture d'écran ci- - dessous. - - \image addressbook-tutorial-part6-save.png - - Si \c fileName n'est pas vide, on crée un objet QFile, \c file, à partir - de \c fileName. QFile fonctionne avec QDataStream puisqu'il dérive de - QIODevice. - - Ensuite, on essaie d'ouvrir le fichier en écriture, ce qui correspond au - mode \l{QIODevice::}{WriteOnly}. Si cela échoue, on en informe - l'utilisateur avec une QMessageBox. - - \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part2 - - Dans le cas contraire, on instancie un objet QDataStream, \c out, afin - d'écrire dans le fichier ouvert. QDataStream nécessite que la même - version de flux soit utilisée pour la lecture et l'écriture. On s'assure - que c'est le cas en spécifiant explicitement d'utiliser la - \l{QDataStream::Qt_4_5}{version introduite avec Qt 4.5} avant de - sérialiser les données vers le fichier \c file. - - \snippet tutorials/addressbook/part6/addressbook.cpp saveToFile() function part3 - - Pour le chargement, on récupère également \c fileName en utilisant - QFileDialog::getOpenFileName(). Cette méthode est l'homologue de - QFileDialog::getSaveFileName() et affiche également une boîte de - dialogue modale permettant à l'utilisateur d'entrer un nom de fichier ou - de selectionner un fichier \c{.abk} existant, afin de le charger dans le - carnet d'adresses. - - \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part1 - - Sous Windows, par exemple, cette méthode affiche une boîte de dialogue - native pour la sélection de fichier, comme illustré sur la capture - d'écran suivante: - - \image addressbook-tutorial-part6-load.png - - Si \c fileName n'est pas vide, on utilise une fois de plus un objet - QFile, \c file, et on tente de l'ouvrir en lecture, avec le mode - \l{QIODevice::}{ReadOnly}. De même que précédemment dans notre - implémentation de \c saveToFile(), si cette tentative s'avère - infructueuse, on en informe l'utilisateur par le biais d'une - QMessageBox. - - \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part2 - - Dans le cas contraire, on instancie un objet QDataStream, \c in, en - spécifiant la version à utiliser comme précédemment, et on lit les - informations sérialisées vers la structure de données \c contacts. Notez - qu'on purge \c contacts avant d'y mettre les informations lues afin de - simplifier le processus de lecture de fichier. Une façon plus avancée de - procéder serait de lire les contacts dans un objet QMap temporaire, et - de copier uniquement les contacts n'existant pas encore dans - \c contacts. - - \snippet tutorials/addressbook/part6/addressbook.cpp loadFromFile() function part3 - - Pour afficher les contacts lus depuis le fichier, on doit d'abord - valider les données obtenues afin de s'assurer que le fichier lu - contient effectivement des entrées de carnet d'adresses. Si c'est le - cas, on affiche le premier contact; sinon on informe l'utilisateur du - problème par une QMessageBox. Enfin, on met à jour l'interface afin - d'activer et de désactiver les boutons de façon appropriée. -*/ - -/*! - \example tutorials/addressbook-fr/part7 - \title Carnet d'adresse 7 - Fonctionnalités avancées - - Ce chapitre couvre quelques fonctionnalités additionnelles qui - feront de notre carnet d'adresses une application plus pratique - pour une utilisation quotidienne. - - \image addressbook-tutorial-part7-screenshot.png - - Bien que notre application carnet d'adresses soit utile en tant que telle, - il serait pratique de pouvoir échanger les contacts avec d'autres applications. - Le format vCard est un un format de fichier populaire pour échanger - ce type de données. - Dans ce chapitre, nous étendrons notre carnet d'adresses pour permettre - d'exporter des contacts dans des fichiers vCard \c{.vcf}. - - \section1 Définition de la classe AddressBook - - Nous ajoutons un objet QPushButton, \c exportButton, et un slot - public correspondant, \c exportAsVCard(), à notre classe \c AddressBook - dans le fichier \c addressbook.h. - - \snippet tutorials/addressbook/part7/addressbook.h exportAsVCard() declaration - \dots - \snippet tutorials/addressbook/part7/addressbook.h exportButton declaration - - \section1 Implémentation de la classe AddressBook - - Dans le constructeur de \c AddressBook, nous connectons le signal - \l{QPushButton::clicked()}{clicked()} de \c{exportButton} au slot - \c exportAsVCard(). - Nous ajoutons aussi ce bouton à \c buttonLayout1, le layout responsable - du groupe de boutons sur la droite. - - Dans la méthode \c exportAsVCard(), nous commençons par extraire le - nom du contact dans \c name. Nous déclarons \c firstname, \c lastName et - \c nameList. - Ensuite, nous cherchons la position du premier espace blanc de \c name. - Si il y a un espace, nous séparons le nom du contact en \c firstName et - \c lastName. Finalement, nous remplaçons l'espace par un underscore ("_"). - Si il n'y a pas d'espace, nous supposons que le contact ne comprend que - le prénom. - - \snippet tutorials/addressbook/part7/addressbook.cpp export function part1 - - Comme pour la méthode \c saveToFile(), nous ouvrons une boîte de dialogue - pour donner la possibilité à l'utilisateur de choisir un emplacement pour - le fichier. Avec le nom de fichier choisi, nous créons une instance de QFile - pour y écrire. - - Nous essayons d'ouvrir le fichier en mode \l{QIODevice::}{WriteOnly}. Si - cela échoue, nous affichons un QMessageBox pour informer l'utilisateur - à propos de l'origine du problème et nous quittons la méthode. Sinon, nous passons le - fichier comme paramètre pour créer un objet QTextStream, \c out. De la même façon que - QDataStream, la classe QTextStream fournit les fonctionnalités pour - lire et écrire des fichiers de texte. Grâce à celà, le fichier \c{.vcf} - généré pourra être ouvert et édité à l'aide d'un simple éditeur de texte. - - \snippet tutorials/addressbook/part7/addressbook.cpp export function part2 - - Nous écrivons ensuite un fichier vCard avec la balise \c{BEGIN:VCARD}, - suivit par \c{VERSION:2.1}. - Le nom d'un contact est écrit à l'aide de la balise \c{N:}. Pour la balise - \c{FN:}, qui remplit le titre du contact, nous devons vérifier si le contact - à un nom de famille défini ou non. Si oui, nous utilions les détails de - \c nameList pour remplir le champ, dans le cas contraire on écrit uniquement le contenu - de \c firstName. - - \snippet tutorials/addressbook/part7/addressbook.cpp export function part3 - - Nous continuons en écrivant l'adresse du contact. Les points-virgules - dans l'adresse sont échappés à l'aide de "\\", les retours de ligne sont - remplacés par des points-virgules, et les vigules sont remplacées par des espaces. - Finalement nous écrivons les balises \c{ADR;HOME:;} suivies par l'adresse - et la balise \c{END:VCARD}. - - \snippet tutorials/addressbook/part7/addressbook.cpp export function part4 - - À la fin de la méthode, un QMessageBox est affiché pour informer l'utilisateur - que la vCard a été exportée avec succès. - - \e{vCard est une marque déposée de \l{http://www.imc.org} - {Internet Mail Consortium}}. -*/ diff --git a/examples/widgets/tutorials/addressbook-fr/README b/examples/widgets/tutorials/addressbook-fr/README deleted file mode 100644 index 07897b9683..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/README +++ /dev/null @@ -1,40 +0,0 @@ -The Address Book Tutorial shows how to put together a simple yet -fully-functioning GUI application. The tutorial chapters can be found in the -Qt documentation, which can be viewed using Qt Assistant or a Web browser. - -The tutorial is also available online at - -http://qt-project.org/doc/qt-5.0/qtwidgets/tutorials-addressbook.html - -All programs corresponding to the chapters in the tutorial should -automatically be built when Qt is compiled, or will be provided as -pre-built executables if you have obtained a binary package of Qt. - -If you have only compiled the Qt libraries, use the following instructions -to build the tutorial. - -On Linux/Unix: - -Typing 'make' in this directory builds all the programs (part1/part1, -part2/part2, part3/part3 and so on). Typing 'make' in each subdirectory -builds just that tutorial program. - -On Windows: - -Create a single Visual Studio project for the tutorial directory in -the usual way. You can do this by typing the following at the command -line: - -qmake -tp vc - -You should now be able to open the project file in Visual Studio and -build all of the tutorial programs at the same time. - -On Mac OS X: - -Create an Xcode project with the .pro file in the tutorial directory. -You can do this by typing the following at the command line: - -qmake -spec macx-xcode - -Then open the generated Xcode project in Xcode and build it. diff --git a/examples/widgets/tutorials/addressbook-fr/addressbook-fr.pro b/examples/widgets/tutorials/addressbook-fr/addressbook-fr.pro deleted file mode 100644 index 8006039ce3..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/addressbook-fr.pro +++ /dev/null @@ -1,7 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = part1 part2 part3 part4 part5 part6 part7 - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook-fr -INSTALLS += target - diff --git a/examples/widgets/tutorials/addressbook-fr/part1/addressbook.cpp b/examples/widgets/tutorials/addressbook-fr/part1/addressbook.cpp deleted file mode 100644 index 60acd6bb27..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part1/addressbook.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -//! [constructor and input fields] -AddressBook::AddressBook(QWidget *parent) - : QWidget(parent) -{ - QLabel *nameLabel = new QLabel(tr("Name:")); - nameLine = new QLineEdit; - - QLabel *addressLabel = new QLabel(tr("Address:")); - addressText = new QTextEdit; -//! [constructor and input fields] - -//! [layout] - QGridLayout *mainLayout = new QGridLayout; - mainLayout->addWidget(nameLabel, 0, 0); - mainLayout->addWidget(nameLine, 0, 1); - mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop); - mainLayout->addWidget(addressText, 1, 1); -//! [layout] - -//![setting the layout] - setLayout(mainLayout); - setWindowTitle(tr("Simple Address Book")); -} -//! [setting the layout] diff --git a/examples/widgets/tutorials/addressbook-fr/part1/main.cpp b/examples/widgets/tutorials/addressbook-fr/part1/main.cpp deleted file mode 100644 index 71f3f4cad6..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part1/main.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -//! [main function] -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - AddressBook addressBook; - addressBook.show(); - - return app.exec(); -} -//! [main function] diff --git a/examples/widgets/tutorials/addressbook-fr/part1/part1.pro b/examples/widgets/tutorials/addressbook-fr/part1/part1.pro deleted file mode 100644 index aa31f122b8..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part1/part1.pro +++ /dev/null @@ -1,13 +0,0 @@ -QT += widgets - -SOURCES = addressbook.cpp \ - main.cpp -HEADERS = addressbook.h - -QMAKE_PROJECT_NAME = abfr_part1 - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook-fr/part1 -INSTALLS += target - -simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/tutorials/addressbook-fr/part2/addressbook.cpp b/examples/widgets/tutorials/addressbook-fr/part2/addressbook.cpp deleted file mode 100644 index d88716a8c8..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part2/addressbook.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -AddressBook::AddressBook(QWidget *parent) - : QWidget(parent) -{ - QLabel *nameLabel = new QLabel(tr("Name:")); - nameLine = new QLineEdit; -//! [setting readonly 1] - nameLine->setReadOnly(true); -//! [setting readonly 1] - QLabel *addressLabel = new QLabel(tr("Address:")); - addressText = new QTextEdit; -//! [setting readonly 2] - addressText->setReadOnly(true); -//! [setting readonly 2] - -//! [pushbutton declaration] - addButton = new QPushButton(tr("&Add")); - addButton->show(); - submitButton = new QPushButton(tr("&Submit")); - submitButton->hide(); - cancelButton = new QPushButton(tr("&Cancel")); - cancelButton->hide(); -//! [pushbutton declaration] -//! [connecting signals and slots] - connect(addButton, SIGNAL(clicked()), this, SLOT(addContact())); - connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); -//! [connecting signals and slots] -//! [vertical layout] - QVBoxLayout *buttonLayout1 = new QVBoxLayout; - buttonLayout1->addWidget(addButton, Qt::AlignTop); - buttonLayout1->addWidget(submitButton); - buttonLayout1->addWidget(cancelButton); - buttonLayout1->addStretch(); -//! [vertical layout] -//! [grid layout] - QGridLayout *mainLayout = new QGridLayout; - mainLayout->addWidget(nameLabel, 0, 0); - mainLayout->addWidget(nameLine, 0, 1); - mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop); - mainLayout->addWidget(addressText, 1, 1); - mainLayout->addLayout(buttonLayout1, 1, 2); -//! [grid layout] - setLayout(mainLayout); - setWindowTitle(tr("Simple Address Book")); -} -//! [addContact] -void AddressBook::addContact() -{ - oldName = nameLine->text(); - oldAddress = addressText->toPlainText(); - - nameLine->clear(); - addressText->clear(); - - nameLine->setReadOnly(false); - nameLine->setFocus(Qt::OtherFocusReason); - addressText->setReadOnly(false); - - addButton->setEnabled(false); - submitButton->show(); - cancelButton->show(); -} -//! [addContact] - -//! [submitContact part1] -void AddressBook::submitContact() -{ - QString name = nameLine->text(); - QString address = addressText->toPlainText(); - - if ( name.isEmpty()|| address.isEmpty()) { - QMessageBox::information(this, tr("Empty Field"), - tr("Please enter a name and address.")); - return; - } -//! [submitContact part1] -//! [submitContact part2] - if (!contacts.contains(name)) { - contacts.insert(name, address); - QMessageBox::information(this, tr("Add Successful"), - tr("\"%1\" has been added to your address book.").arg(name)); - } else { - QMessageBox::information(this, tr("Add Unsuccessful"), - tr("Sorry, \"%1\" is already in your address book.").arg(name)); - return; - } -//! [submitContact part2] -//! [submitContact part3] - if (contacts.isEmpty()) { - nameLine->clear(); - addressText->clear(); - } - - nameLine->setReadOnly(true); - addressText->setReadOnly(true); - addButton->setEnabled(true); - submitButton->hide(); - cancelButton->hide(); -} -//! [submitContact part3] -//! [cancel] -void AddressBook::cancel() -{ - nameLine->setText(oldName); - nameLine->setReadOnly(true); - - addressText->setText(oldAddress); - addressText->setReadOnly(true); - - addButton->setEnabled(true); - submitButton->hide(); - cancelButton->hide(); -} -//! [cancel] diff --git a/examples/widgets/tutorials/addressbook-fr/part2/main.cpp b/examples/widgets/tutorials/addressbook-fr/part2/main.cpp deleted file mode 100644 index 71f3f4cad6..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part2/main.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -//! [main function] -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - AddressBook addressBook; - addressBook.show(); - - return app.exec(); -} -//! [main function] diff --git a/examples/widgets/tutorials/addressbook-fr/part2/part2.pro b/examples/widgets/tutorials/addressbook-fr/part2/part2.pro deleted file mode 100644 index bfcedda6f7..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part2/part2.pro +++ /dev/null @@ -1,13 +0,0 @@ -QT += widgets - -SOURCES = addressbook.cpp \ - main.cpp -HEADERS = addressbook.h - -QMAKE_PROJECT_NAME = abfr_part2 - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook-fr/part2 -INSTALLS += target - -simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/tutorials/addressbook-fr/part3/addressbook.cpp b/examples/widgets/tutorials/addressbook-fr/part3/addressbook.cpp deleted file mode 100644 index 86ff58d015..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part3/addressbook.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -AddressBook::AddressBook(QWidget *parent) - : QWidget(parent) -{ - QLabel *nameLabel = new QLabel(tr("Name:")); - nameLine = new QLineEdit; - nameLine->setReadOnly(true); - - QLabel *addressLabel = new QLabel(tr("Address:")); - addressText = new QTextEdit; - addressText->setReadOnly(true); - - addButton = new QPushButton(tr("&Add")); - addButton->show(); - submitButton = new QPushButton(tr("&Submit")); - submitButton->hide(); - cancelButton = new QPushButton(tr("&Cancel")); - cancelButton->hide(); -//! [navigation pushbuttons] - nextButton = new QPushButton(tr("&Next")); - nextButton->setEnabled(false); - previousButton = new QPushButton(tr("&Previous")); - previousButton->setEnabled(false); -//! [navigation pushbuttons] - - connect(addButton, SIGNAL(clicked()), this, SLOT(addContact())); - connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); -//! [connecting navigation signals] - connect(nextButton, SIGNAL(clicked()), this, SLOT(next())); - connect(previousButton, SIGNAL(clicked()), this, SLOT(previous())); -//! [connecting navigation signals] - - QVBoxLayout *buttonLayout1 = new QVBoxLayout; - buttonLayout1->addWidget(addButton, Qt::AlignTop); - buttonLayout1->addWidget(submitButton); - buttonLayout1->addWidget(cancelButton); - buttonLayout1->addStretch(); -//! [navigation layout] - QHBoxLayout *buttonLayout2 = new QHBoxLayout; - buttonLayout2->addWidget(previousButton); - buttonLayout2->addWidget(nextButton); -//! [ navigation layout] - QGridLayout *mainLayout = new QGridLayout; - mainLayout->addWidget(nameLabel, 0, 0); - mainLayout->addWidget(nameLine, 0, 1); - mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop); - mainLayout->addWidget(addressText, 1, 1); - mainLayout->addLayout(buttonLayout1, 1, 2); -//! [adding navigation layout] - mainLayout->addLayout(buttonLayout2, 3, 1); -//! [adding navigation layout] - setLayout(mainLayout); - setWindowTitle(tr("Simple Address Book")); -} - -void AddressBook::addContact() -{ - oldName = nameLine->text(); - oldAddress = addressText->toPlainText(); - - nameLine->clear(); - addressText->clear(); - - nameLine->setReadOnly(false); - nameLine->setFocus(Qt::OtherFocusReason); - addressText->setReadOnly(false); - - addButton->setEnabled(false); -//! [disabling navigation] - nextButton->setEnabled(false); - previousButton->setEnabled(false); -//! [disabling navigation] - submitButton->show(); - cancelButton->show(); -} - -void AddressBook::submitContact() -{ - QString name = nameLine->text(); - QString address = addressText->toPlainText(); - - if (name.isEmpty() || address.isEmpty()) { - QMessageBox::information(this, tr("Empty Field"), - tr("Please enter a name and address.")); - return; - } - - if (!contacts.contains(name)) { - contacts.insert(name, address); - QMessageBox::information(this, tr("Add Successful"), - tr("\"%1\" has been added to your address book.").arg(name)); - } else { - QMessageBox::information(this, tr("Add Unsuccessful"), - tr("Sorry, \"%1\" is already in your address book.").arg(name)); - } - - if (contacts.isEmpty()) { - nameLine->clear(); - addressText->clear(); - } - - nameLine->setReadOnly(true); - addressText->setReadOnly(true); - addButton->setEnabled(true); - -//! [enabling navigation] - int number = contacts.size(); - nextButton->setEnabled(number > 1); - previousButton->setEnabled(number > 1); -//! [enabling navigation] - submitButton->hide(); - cancelButton->hide(); -} - -void AddressBook::cancel() -{ - nameLine->setText(oldName); - addressText->setText(oldAddress); - - if (contacts.isEmpty()) { - nameLine->clear(); - addressText->clear(); - } - - nameLine->setReadOnly(true); - addressText->setReadOnly(true); - addButton->setEnabled(true); - - int number = contacts.size(); - nextButton->setEnabled(number > 1); - previousButton->setEnabled(number > 1); - - submitButton->hide(); - cancelButton->hide(); -} - -//! [next() function] -void AddressBook::next() -{ - QString name = nameLine->text(); - QMap<QString, QString>::iterator i = contacts.find(name); - - if (i != contacts.end()) - i++; - - if (i == contacts.end()) - i = contacts.begin(); - - nameLine->setText(i.key()); - addressText->setText(i.value()); -} -//! [next() function] -//! [previous() function] -void AddressBook::previous() -{ - QString name = nameLine->text(); - QMap<QString, QString>::iterator i = contacts.find(name); - - if (i == contacts.end()){ - nameLine->clear(); - addressText->clear(); - return; - } - - if (i == contacts.begin()) - i = contacts.end(); - - i--; - nameLine->setText(i.key()); - addressText->setText(i.value()); -} -//! [previous() function] diff --git a/examples/widgets/tutorials/addressbook-fr/part3/addressbook.h b/examples/widgets/tutorials/addressbook-fr/part3/addressbook.h deleted file mode 100644 index 3613fedb34..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part3/addressbook.h +++ /dev/null @@ -1,86 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ADDRESSBOOK_H -#define ADDRESSBOOK_H - -#include <QWidget> -#include <QMap> - -QT_BEGIN_NAMESPACE -class QLabel; -class QLineEdit; -class QPushButton; -class QTextEdit; -QT_END_NAMESPACE - -class AddressBook : public QWidget -{ - Q_OBJECT - -public: - AddressBook(QWidget *parent = 0); - -public slots: - void addContact(); - void submitContact(); - void cancel(); -//! [navigation functions] - void next(); - void previous(); -//! [navigation functions] - -private: - QPushButton *addButton; - QPushButton *submitButton; - QPushButton *cancelButton; -//! [navigation pushbuttons] - QPushButton *nextButton; - QPushButton *previousButton; -//! [navigation pushbuttons] - QLineEdit *nameLine; - QTextEdit *addressText; - - QMap<QString, QString> contacts; - QString oldName; - QString oldAddress; -}; - -#endif diff --git a/examples/widgets/tutorials/addressbook-fr/part3/main.cpp b/examples/widgets/tutorials/addressbook-fr/part3/main.cpp deleted file mode 100644 index 70eabab255..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part3/main.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - AddressBook addressBook; - addressBook.show(); - - return app.exec(); -} diff --git a/examples/widgets/tutorials/addressbook-fr/part3/part3.pro b/examples/widgets/tutorials/addressbook-fr/part3/part3.pro deleted file mode 100644 index 0990cb5088..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part3/part3.pro +++ /dev/null @@ -1,13 +0,0 @@ -QT += widgets - -SOURCES = addressbook.cpp \ - main.cpp -HEADERS = addressbook.h - -QMAKE_PROJECT_NAME = abfr_part3 - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook-fr/part3 -INSTALLS += target - -simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/tutorials/addressbook-fr/part4/addressbook.cpp b/examples/widgets/tutorials/addressbook-fr/part4/addressbook.cpp deleted file mode 100644 index 70f5d110db..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part4/addressbook.cpp +++ /dev/null @@ -1,288 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -AddressBook::AddressBook(QWidget *parent) - : QWidget(parent) -{ - QLabel *nameLabel = new QLabel(tr("Name:")); - nameLine = new QLineEdit; - nameLine->setReadOnly(true); - - QLabel *addressLabel = new QLabel(tr("Address:")); - addressText = new QTextEdit; - addressText->setReadOnly(true); - - addButton = new QPushButton(tr("&Add")); -//! [edit and remove buttons] - editButton = new QPushButton(tr("&Edit")); - editButton->setEnabled(false); - removeButton = new QPushButton(tr("&Remove")); - removeButton->setEnabled(false); -//! [edit and remove buttons] - submitButton = new QPushButton(tr("&Submit")); - submitButton->hide(); - cancelButton = new QPushButton(tr("&Cancel")); - cancelButton->hide(); - - nextButton = new QPushButton(tr("&Next")); - nextButton->setEnabled(false); - previousButton = new QPushButton(tr("&Previous")); - previousButton->setEnabled(false); - - connect(addButton, SIGNAL(clicked()), this, SLOT(addContact())); - connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact())); -//! [connecting edit and remove] - connect(editButton, SIGNAL(clicked()), this, SLOT(editContact())); - connect(removeButton, SIGNAL(clicked()), this, SLOT(removeContact())); -//! [connecting edit and remove] - connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); - connect(nextButton, SIGNAL(clicked()), this, SLOT(next())); - connect(previousButton, SIGNAL(clicked()), this, SLOT(previous())); - - QVBoxLayout *buttonLayout1 = new QVBoxLayout; - buttonLayout1->addWidget(addButton); -//! [adding edit and remove to the layout] - buttonLayout1->addWidget(editButton); - buttonLayout1->addWidget(removeButton); -//! [adding edit and remove to the layout] - buttonLayout1->addWidget(submitButton); - buttonLayout1->addWidget(cancelButton); - buttonLayout1->addStretch(); - - QHBoxLayout *buttonLayout2 = new QHBoxLayout; - buttonLayout2->addWidget(previousButton); - buttonLayout2->addWidget(nextButton); - - QGridLayout *mainLayout = new QGridLayout; - mainLayout->addWidget(nameLabel, 0, 0); - mainLayout->addWidget(nameLine, 0, 1); - mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop); - mainLayout->addWidget(addressText, 1, 1); - mainLayout->addLayout(buttonLayout1, 1, 2); - mainLayout->addLayout(buttonLayout2, 3, 1); - - setLayout(mainLayout); - setWindowTitle(tr("Simple Address Book")); -} - -void AddressBook::addContact() -{ - oldName = nameLine->text(); - oldAddress = addressText->toPlainText(); - - nameLine->clear(); - addressText->clear(); - - updateInterface(AddingMode); -} -//! [editContact() function] -void AddressBook::editContact() -{ - oldName = nameLine->text(); - oldAddress = addressText->toPlainText(); - - updateInterface(EditingMode); -} -//! [editContact() function] -//! [submitContact() function beginning] -void AddressBook::submitContact() -{ -//! [submitContact() function beginning] - QString name = nameLine->text(); - QString address = addressText->toPlainText(); - - if (name.isEmpty() || address.isEmpty()) { - QMessageBox::information(this, tr("Empty Field"), - tr("Please enter a name and address.")); - return; - } -//! [submitContact() function part1] - if (currentMode == AddingMode) { - - if (!contacts.contains(name)) { - contacts.insert(name, address); - QMessageBox::information(this, tr("Add Successful"), - tr("\"%1\" has been added to your address book.").arg(name)); - } else { - QMessageBox::information(this, tr("Add Unsuccessful"), - tr("Sorry, \"%1\" is already in your address book.").arg(name)); - } -//! [submitContact() function part1] -//! [submitContact() function part2] - } else if (currentMode == EditingMode) { - - if (oldName != name) { - if (!contacts.contains(name)) { - QMessageBox::information(this, tr("Edit Successful"), - tr("\"%1\" has been edited in your address book.").arg(oldName)); - contacts.remove(oldName); - contacts.insert(name, address); - } else { - QMessageBox::information(this, tr("Edit Unsuccessful"), - tr("Sorry, \"%1\" is already in your address book.").arg(name)); - } - } else if (oldAddress != address) { - QMessageBox::information(this, tr("Edit Successful"), - tr("\"%1\" has been edited in your address book.").arg(name)); - contacts[name] = address; - } - } - - updateInterface(NavigationMode); -} -//! [submitContact() function part2] - -void AddressBook::cancel() -{ - nameLine->setText(oldName); - addressText->setText(oldAddress); - updateInterface(NavigationMode); -} -//! [removeContact() function] -void AddressBook::removeContact() -{ - QString name = nameLine->text(); - QString address = addressText->toPlainText(); - - if (contacts.contains(name)) { - - int button = QMessageBox::question(this, - tr("Confirm Remove"), - tr("Are you sure you want to remove \"%1\"?").arg(name), - QMessageBox::Yes | QMessageBox::No); - - if (button == QMessageBox::Yes) { - - previous(); - contacts.remove(name); - - QMessageBox::information(this, tr("Remove Successful"), - tr("\"%1\" has been removed from your address book.").arg(name)); - } - } - - updateInterface(NavigationMode); -} -//! [removeContact() function] -void AddressBook::next() -{ - QString name = nameLine->text(); - QMap<QString, QString>::iterator i = contacts.find(name); - - if (i != contacts.end()) - i++; - - if (i == contacts.end()) - i = contacts.begin(); - - nameLine->setText(i.key()); - addressText->setText(i.value()); -} - -void AddressBook::previous() -{ - QString name = nameLine->text(); - QMap<QString, QString>::iterator i = contacts.find(name); - - if (i == contacts.end()) { - nameLine->clear(); - addressText->clear(); - return; - } - - if (i == contacts.begin()) - i = contacts.end(); - - i--; - nameLine->setText(i.key()); - addressText->setText(i.value()); -} -//! [update interface() part 1] -void AddressBook::updateInterface(Mode mode) -{ - currentMode = mode; - - switch (currentMode) { - - case AddingMode: - case EditingMode: - - nameLine->setReadOnly(false); - nameLine->setFocus(Qt::OtherFocusReason); - addressText->setReadOnly(false); - - addButton->setEnabled(false); - editButton->setEnabled(false); - removeButton->setEnabled(false); - - nextButton->setEnabled(false); - previousButton->setEnabled(false); - - submitButton->show(); - cancelButton->show(); - break; -//! [update interface() part 1] -//! [update interface() part 2] - case NavigationMode: - - if (contacts.isEmpty()) { - nameLine->clear(); - addressText->clear(); - } - - nameLine->setReadOnly(true); - addressText->setReadOnly(true); - addButton->setEnabled(true); - - int number = contacts.size(); - editButton->setEnabled(number >= 1); - removeButton->setEnabled(number >= 1); - nextButton->setEnabled(number > 1); - previousButton->setEnabled(number >1 ); - - submitButton->hide(); - cancelButton->hide(); - break; - } -} -//! [update interface() part 2] diff --git a/examples/widgets/tutorials/addressbook-fr/part4/addressbook.h b/examples/widgets/tutorials/addressbook-fr/part4/addressbook.h deleted file mode 100644 index 6430ac3413..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part4/addressbook.h +++ /dev/null @@ -1,99 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ADDRESSBOOK_H -#define ADDRESSBOOK_H - -#include <QWidget> -#include <QMap> - -QT_BEGIN_NAMESPACE -class QPushButton; -class QLabel; -class QLineEdit; -class QTextEdit; -QT_END_NAMESPACE - -class AddressBook : public QWidget -{ - Q_OBJECT - -public: - AddressBook(QWidget *parent = 0); -//! [Mode enum] - enum Mode { NavigationMode, AddingMode, EditingMode }; -//! [Mode enum] - -public slots: - void addContact(); - void submitContact(); - void cancel(); -//! [edit and remove slots] - void editContact(); - void removeContact(); -//! [edit and remove slots] - void next(); - void previous(); - -private: -//! [updateInterface() declaration] - void updateInterface(Mode mode); -//! [updateInterface() declaration] - QPushButton *addButton; -//! [buttons declaration] - QPushButton *editButton; - QPushButton *removeButton; -//! [buttons declaration] - QPushButton *submitButton; - QPushButton *cancelButton; - QPushButton *nextButton; - QPushButton *previousButton; - QLineEdit *nameLine; - QTextEdit *addressText; - - QMap<QString, QString> contacts; - QString oldName; - QString oldAddress; -//! [mode declaration] - Mode currentMode; -//! [mode declaration] -}; - -#endif diff --git a/examples/widgets/tutorials/addressbook-fr/part4/part4.pro b/examples/widgets/tutorials/addressbook-fr/part4/part4.pro deleted file mode 100644 index 44ff4bdce9..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part4/part4.pro +++ /dev/null @@ -1,13 +0,0 @@ -QT += widgets - -SOURCES = addressbook.cpp \ - main.cpp -HEADERS = addressbook.h - -QMAKE_PROJECT_NAME = abfr_part4 - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook-fr/part4 -INSTALLS += target - -simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/tutorials/addressbook-fr/part5/addressbook.cpp b/examples/widgets/tutorials/addressbook-fr/part5/addressbook.cpp deleted file mode 100644 index 33af5f1e4e..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part5/addressbook.cpp +++ /dev/null @@ -1,312 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -AddressBook::AddressBook(QWidget *parent) - : QWidget(parent) -{ - QLabel *nameLabel = new QLabel(tr("Name:")); - nameLine = new QLineEdit; - nameLine->setReadOnly(true); - - QLabel *addressLabel = new QLabel(tr("Address:")); - addressText = new QTextEdit; - addressText->setReadOnly(true); - - addButton = new QPushButton(tr("&Add")); - - editButton = new QPushButton(tr("&Edit")); - editButton->setEnabled(false); - removeButton = new QPushButton(tr("&Remove")); - removeButton->setEnabled(false); -//! [instantiating findButton] - findButton = new QPushButton(tr("&Find")); - findButton->setEnabled(false); -//! [instantiating findButton] - submitButton = new QPushButton(tr("&Submit")); - submitButton->hide(); - cancelButton = new QPushButton(tr("&Cancel")); - cancelButton->hide(); - - nextButton = new QPushButton(tr("&Next")); - nextButton->setEnabled(false); - previousButton = new QPushButton(tr("&Previous")); - previousButton->setEnabled(false); - -//! [instantiating FindDialog] - dialog = new FindDialog; -//! [instantiating FindDialog] - - connect(addButton, SIGNAL(clicked()), this, SLOT(addContact())); - connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact())); - connect(editButton, SIGNAL(clicked()), this, SLOT(editContact())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); - connect(removeButton, SIGNAL(clicked()), this, SLOT(removeContact())); -//! [signals and slots for find] - connect(findButton, SIGNAL(clicked()), this, SLOT(findContact())); -//! [signals and slots for find] - connect(nextButton, SIGNAL(clicked()), this, SLOT(next())); - connect(previousButton, SIGNAL(clicked()), this, SLOT(previous())); - - QVBoxLayout *buttonLayout1 = new QVBoxLayout; - buttonLayout1->addWidget(addButton); - buttonLayout1->addWidget(editButton); - buttonLayout1->addWidget(removeButton); -//! [adding findButton to layout] - buttonLayout1->addWidget(findButton); -//! [adding findButton to layout] - buttonLayout1->addWidget(submitButton); - buttonLayout1->addWidget(cancelButton); - buttonLayout1->addStretch(); - - QHBoxLayout *buttonLayout2 = new QHBoxLayout; - buttonLayout2->addWidget(previousButton); - buttonLayout2->addWidget(nextButton); - - QGridLayout *mainLayout = new QGridLayout; - mainLayout->addWidget(nameLabel, 0, 0); - mainLayout->addWidget(nameLine, 0, 1); - mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop); - mainLayout->addWidget(addressText, 1, 1); - mainLayout->addLayout(buttonLayout1, 1, 2); - mainLayout->addLayout(buttonLayout2, 2, 1); - - setLayout(mainLayout); - setWindowTitle(tr("Simple Address Book")); -} - -void AddressBook::addContact() -{ - oldName = nameLine->text(); - oldAddress = addressText->toPlainText(); - - nameLine->clear(); - addressText->clear(); - - updateInterface(AddingMode); -} - -void AddressBook::editContact() -{ - oldName = nameLine->text(); - oldAddress = addressText->toPlainText(); - - updateInterface(EditingMode); -} - -void AddressBook::submitContact() -{ - QString name = nameLine->text(); - QString address = addressText->toPlainText(); - - if (name.isEmpty() || address.isEmpty()) { - QMessageBox::information(this, tr("Empty Field"), - tr("Please enter a name and address.")); - return; - } - - if (currentMode == AddingMode) { - - if (!contacts.contains(name)) { - contacts.insert(name, address); - QMessageBox::information(this, tr("Add Successful"), - tr("\"%1\" has been added to your address book.").arg(name)); - } else { - QMessageBox::information(this, tr("Add Unsuccessful"), - tr("Sorry, \"%1\" is already in your address book.").arg(name)); - } - } else if (currentMode == EditingMode) { - - if (oldName != name) { - if (!contacts.contains(name)) { - QMessageBox::information(this, tr("Edit Successful"), - tr("\"%1\" has been edited in your address book.").arg(oldName)); - contacts.remove(oldName); - contacts.insert(name, address); - } else { - QMessageBox::information(this, tr("Edit Unsuccessful"), - tr("Sorry, \"%1\" is already in your address book.").arg(name)); - } - } else if (oldAddress != address) { - QMessageBox::information(this, tr("Edit Successful"), - tr("\"%1\" has been edited in your address book.").arg(name)); - contacts[name] = address; - } - } - - updateInterface(NavigationMode); -} - -void AddressBook::cancel() -{ - nameLine->setText(oldName); - addressText->setText(oldAddress); - updateInterface(NavigationMode); -} - -void AddressBook::removeContact() -{ - QString name = nameLine->text(); - QString address = addressText->toPlainText(); - - if (contacts.contains(name)) { - - int button = QMessageBox::question(this, - tr("Confirm Remove"), - tr("Are you sure you want to remove \"%1\"?").arg(name), - QMessageBox::Yes | QMessageBox::No); - - if (button == QMessageBox::Yes) { - - previous(); - contacts.remove(name); - - QMessageBox::information(this, tr("Remove Successful"), - tr("\"%1\" has been removed from your address book.").arg(name)); - } - } - - updateInterface(NavigationMode); -} - -void AddressBook::next() -{ - QString name = nameLine->text(); - QMap<QString, QString>::iterator i = contacts.find(name); - - if (i != contacts.end()) - i++; - - if (i == contacts.end()) - i = contacts.begin(); - - nameLine->setText(i.key()); - addressText->setText(i.value()); -} - -void AddressBook::previous() -{ - QString name = nameLine->text(); - QMap<QString, QString>::iterator i = contacts.find(name); - - if (i == contacts.end()) { - nameLine->clear(); - addressText->clear(); - return; - } - - if (i == contacts.begin()) - i = contacts.end(); - - i--; - nameLine->setText(i.key()); - addressText->setText(i.value()); -} -//! [findContact() function] -void AddressBook::findContact() -{ - dialog->show(); - - if (dialog->exec() == QDialog::Accepted) { - QString contactName = dialog->getFindText(); - - if (contacts.contains(contactName)) { - nameLine->setText(contactName); - addressText->setText(contacts.value(contactName)); - } else { - QMessageBox::information(this, tr("Contact Not Found"), - tr("Sorry, \"%1\" is not in your address book.").arg(contactName)); - return; - } - } - - updateInterface(NavigationMode); -} -//! [findContact() function] - -void AddressBook::updateInterface(Mode mode) -{ - currentMode = mode; - - switch (currentMode) { - - case AddingMode: - case EditingMode: - - nameLine->setReadOnly(false); - nameLine->setFocus(Qt::OtherFocusReason); - addressText->setReadOnly(false); - - addButton->setEnabled(false); - editButton->setEnabled(false); - removeButton->setEnabled(false); - - nextButton->setEnabled(false); - previousButton->setEnabled(false); - - submitButton->show(); - cancelButton->show(); - break; - - case NavigationMode: - - if (contacts.isEmpty()) { - nameLine->clear(); - addressText->clear(); - } - - nameLine->setReadOnly(true); - addressText->setReadOnly(true); - addButton->setEnabled(true); - - int number = contacts.size(); - editButton->setEnabled(number >= 1); - removeButton->setEnabled(number >= 1); - findButton->setEnabled(number > 2); - nextButton->setEnabled(number > 1); - previousButton->setEnabled(number > 1); - - submitButton->hide(); - cancelButton->hide(); - break; - } -} diff --git a/examples/widgets/tutorials/addressbook-fr/part5/addressbook.h b/examples/widgets/tutorials/addressbook-fr/part5/addressbook.h deleted file mode 100644 index f8a53304ee..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part5/addressbook.h +++ /dev/null @@ -1,102 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ADDRESSBOOK_H -#define ADDRESSBOOK_H - -#include <QWidget> -#include <QMap> -//! [include finddialog's header] -#include "finddialog.h" -//! [include finddialog's header] -QT_BEGIN_NAMESPACE -class QPushButton; -class QLabel; -class QLineEdit; -class QTextEdit; -QT_END_NAMESPACE - - -class AddressBook : public QWidget -{ - Q_OBJECT - -public: - AddressBook(QWidget *parent = 0); - enum Mode { NavigationMode, AddingMode, EditingMode }; - -public slots: - void addContact(); - void editContact(); - void submitContact(); - void cancel(); - void removeContact(); -//! [findContact() declaration] - void findContact(); -//! [findContact() declaration] - void next(); - void previous(); - -private: - void updateInterface(Mode mode); - - QPushButton *addButton; - QPushButton *editButton; - QPushButton *removeButton; -//! [findButton declaration] - QPushButton *findButton; -//! [findButton declaration] - QPushButton *submitButton; - QPushButton *cancelButton; - QPushButton *nextButton; - QPushButton *previousButton; - QLineEdit *nameLine; - QTextEdit *addressText; - - QMap<QString, QString> contacts; -//! [FindDialog declaration] - FindDialog *dialog; -//! [FindDialog declaration] - QString oldName; - QString oldAddress; - Mode currentMode; -}; - -#endif diff --git a/examples/widgets/tutorials/addressbook-fr/part5/finddialog.cpp b/examples/widgets/tutorials/addressbook-fr/part5/finddialog.cpp deleted file mode 100644 index 303f3d5b08..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part5/finddialog.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "finddialog.h" - -//! [constructor] -FindDialog::FindDialog(QWidget *parent) - : QDialog(parent) -{ - QLabel *findLabel = new QLabel(tr("Enter the name of a contact:")); - lineEdit = new QLineEdit; - - findButton = new QPushButton(tr("&Find")); - findText = ""; - - QHBoxLayout *layout = new QHBoxLayout; - layout->addWidget(findLabel); - layout->addWidget(lineEdit); - layout->addWidget(findButton); - - setLayout(layout); - setWindowTitle(tr("Find a Contact")); - connect(findButton, SIGNAL(clicked()), this, SLOT(findClicked())); - connect(findButton, SIGNAL(clicked()), this, SLOT(accept())); -} -//! [constructor] -//! [findClicked() function] -void FindDialog::findClicked() -{ - QString text = lineEdit->text(); - - if (text.isEmpty()) { - QMessageBox::information(this, tr("Empty Field"), - tr("Please enter a name.")); - return; - } else { - findText = text; - lineEdit->clear(); - hide(); - } -} -//! [findClicked() function] -//! [getFindText() function] -QString FindDialog::getFindText() -{ - return findText; -} -//! [getFindText() function] diff --git a/examples/widgets/tutorials/addressbook-fr/part5/finddialog.h b/examples/widgets/tutorials/addressbook-fr/part5/finddialog.h deleted file mode 100644 index 2b9c4e08de..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part5/finddialog.h +++ /dev/null @@ -1,68 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef FINDDIALOG_H -#define FINDDIALOG_H -//! [FindDialog header] -#include <QDialog> - -QT_BEGIN_NAMESPACE -class QLineEdit; -class QPushButton; -QT_END_NAMESPACE - -class FindDialog : public QDialog -{ - Q_OBJECT - -public: - FindDialog(QWidget *parent = 0); - QString getFindText(); - -public slots: - void findClicked(); - -private: - QPushButton *findButton; - QLineEdit *lineEdit; - QString findText; -}; -//! [FindDialog header] -#endif diff --git a/examples/widgets/tutorials/addressbook-fr/part5/main.cpp b/examples/widgets/tutorials/addressbook-fr/part5/main.cpp deleted file mode 100644 index 70eabab255..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part5/main.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - AddressBook addressBook; - addressBook.show(); - - return app.exec(); -} diff --git a/examples/widgets/tutorials/addressbook-fr/part5/part5.pro b/examples/widgets/tutorials/addressbook-fr/part5/part5.pro deleted file mode 100644 index 10638759a9..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part5/part5.pro +++ /dev/null @@ -1,15 +0,0 @@ -QT += widgets - -SOURCES = addressbook.cpp \ - finddialog.cpp \ - main.cpp -HEADERS = addressbook.h \ - finddialog.h - -QMAKE_PROJECT_NAME = abfr_part5 - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook-fr/part5 -INSTALLS += target - -simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/tutorials/addressbook-fr/part6/addressbook.cpp b/examples/widgets/tutorials/addressbook-fr/part6/addressbook.cpp deleted file mode 100644 index e81c959c2c..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part6/addressbook.cpp +++ /dev/null @@ -1,393 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -AddressBook::AddressBook(QWidget *parent) - : QWidget(parent) -{ - QLabel *nameLabel = new QLabel(tr("Name:")); - nameLine = new QLineEdit; - nameLine->setReadOnly(true); - - QLabel *addressLabel = new QLabel(tr("Address:")); - addressText = new QTextEdit; - addressText->setReadOnly(true); - - addButton = new QPushButton(tr("&Add")); - - editButton = new QPushButton(tr("&Edit")); - editButton->setEnabled(false); - removeButton = new QPushButton(tr("&Remove")); - removeButton->setEnabled(false); - findButton = new QPushButton(tr("&Find")); - findButton->setEnabled(false); - submitButton = new QPushButton(tr("&Submit")); - submitButton->hide(); - cancelButton = new QPushButton(tr("&Cancel")); - cancelButton->hide(); - - nextButton = new QPushButton(tr("&Next")); - nextButton->setEnabled(false); - previousButton = new QPushButton(tr("&Previous")); - previousButton->setEnabled(false); - - loadButton = new QPushButton(tr("&Load...")); -//! [tooltip 1] - loadButton->setToolTip(tr("Load contacts from a file")); -//! [tooltip 1] - saveButton = new QPushButton(tr("Sa&ve...")); -//! [tooltip 2] - saveButton->setToolTip(tr("Save contacts to a file")); -//! [tooltip 2] - saveButton->setEnabled(false); - - dialog = new FindDialog; - - connect(addButton, SIGNAL(clicked()), this, SLOT(addContact())); - connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact())); - connect(editButton, SIGNAL(clicked()), this, SLOT(editContact())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); - connect(removeButton, SIGNAL(clicked()), this, SLOT(removeContact())); - connect(findButton, SIGNAL(clicked()), this, SLOT(findContact())); - connect(nextButton, SIGNAL(clicked()), this, SLOT(next())); - connect(previousButton, SIGNAL(clicked()), this, SLOT(previous())); - connect(loadButton, SIGNAL(clicked()), this, SLOT(loadFromFile())); - connect(saveButton, SIGNAL(clicked()), this, SLOT(saveToFile())); - - QVBoxLayout *buttonLayout1 = new QVBoxLayout; - buttonLayout1->addWidget(addButton); - buttonLayout1->addWidget(editButton); - buttonLayout1->addWidget(removeButton); - buttonLayout1->addWidget(findButton); - buttonLayout1->addWidget(submitButton); - buttonLayout1->addWidget(cancelButton); - buttonLayout1->addWidget(loadButton); - buttonLayout1->addWidget(saveButton); - buttonLayout1->addStretch(); - - QHBoxLayout *buttonLayout2 = new QHBoxLayout; - buttonLayout2->addWidget(previousButton); - buttonLayout2->addWidget(nextButton); - - QGridLayout *mainLayout = new QGridLayout; - mainLayout->addWidget(nameLabel, 0, 0); - mainLayout->addWidget(nameLine, 0, 1); - mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop); - mainLayout->addWidget(addressText, 1, 1); - mainLayout->addLayout(buttonLayout1, 1, 2); - mainLayout->addLayout(buttonLayout2, 2, 1); - - setLayout(mainLayout); - setWindowTitle(tr("Simple Address Book")); -} - -void AddressBook::addContact() -{ - oldName = nameLine->text(); - oldAddress = addressText->toPlainText(); - - nameLine->clear(); - addressText->clear(); - - updateInterface(AddingMode); -} - -void AddressBook::editContact() -{ - oldName = nameLine->text(); - oldAddress = addressText->toPlainText(); - - updateInterface(EditingMode); -} - -void AddressBook::submitContact() -{ - QString name = nameLine->text(); - QString address = addressText->toPlainText(); - - if (name.isEmpty() || address.isEmpty()) { - QMessageBox::information(this, tr("Empty Field"), - tr("Please enter a name and address.")); - return; - } - - if (currentMode == AddingMode) { - - if (!contacts.contains(name)) { - contacts.insert(name, address); - QMessageBox::information(this, tr("Add Successful"), - tr("\"%1\" has been added to your address book.").arg(name)); - } else { - QMessageBox::information(this, tr("Add Unsuccessful"), - tr("Sorry, \"%1\" is already in your address book.").arg(name)); - } - } else if (currentMode == EditingMode) { - - if (oldName != name) { - if (!contacts.contains(name)) { - QMessageBox::information(this, tr("Edit Successful"), - tr("\"%1\" has been edited in your address book.").arg(oldName)); - contacts.remove(oldName); - contacts.insert(name, address); - } else { - QMessageBox::information(this, tr("Edit Unsuccessful"), - tr("Sorry, \"%1\" is already in your address book.").arg(name)); - } - } else if (oldAddress != address) { - QMessageBox::information(this, tr("Edit Successful"), - tr("\"%1\" has been edited in your address book.").arg(name)); - contacts[name] = address; - } - } - - updateInterface(NavigationMode); -} - -void AddressBook::cancel() -{ - nameLine->setText(oldName); - addressText->setText(oldAddress); - updateInterface(NavigationMode); -} - -void AddressBook::removeContact() -{ - QString name = nameLine->text(); - QString address = addressText->toPlainText(); - - if (contacts.contains(name)) { - - int button = QMessageBox::question(this, - tr("Confirm Remove"), - tr("Are you sure you want to remove \"%1\"?").arg(name), - QMessageBox::Yes | QMessageBox::No); - - if (button == QMessageBox::Yes) { - - previous(); - contacts.remove(name); - - QMessageBox::information(this, tr("Remove Successful"), - tr("\"%1\" has been removed from your address book.").arg(name)); - } - } - - updateInterface(NavigationMode); -} - -void AddressBook::next() -{ - QString name = nameLine->text(); - QMap<QString, QString>::iterator i = contacts.find(name); - - if (i != contacts.end()) - i++; - - if (i == contacts.end()) - i = contacts.begin(); - - nameLine->setText(i.key()); - addressText->setText(i.value()); -} - -void AddressBook::previous() -{ - QString name = nameLine->text(); - QMap<QString, QString>::iterator i = contacts.find(name); - - if (i == contacts.end()) { - nameLine->clear(); - addressText->clear(); - return; - } - - if (i == contacts.begin()) - i = contacts.end(); - - i--; - nameLine->setText(i.key()); - addressText->setText(i.value()); -} - -void AddressBook::findContact() -{ - dialog->show(); - - if (dialog->exec() == 1) { - QString contactName = dialog->getFindText(); - - if (contacts.contains(contactName)) { - nameLine->setText(contactName); - addressText->setText(contacts.value(contactName)); - } else { - QMessageBox::information(this, tr("Contact Not Found"), - tr("Sorry, \"%1\" is not in your address book.").arg(contactName)); - return; - } - } - - updateInterface(NavigationMode); -} - -void AddressBook::updateInterface(Mode mode) -{ - currentMode = mode; - - switch (currentMode) { - - case AddingMode: - case EditingMode: - - nameLine->setReadOnly(false); - nameLine->setFocus(Qt::OtherFocusReason); - addressText->setReadOnly(false); - - addButton->setEnabled(false); - editButton->setEnabled(false); - removeButton->setEnabled(false); - - nextButton->setEnabled(false); - previousButton->setEnabled(false); - - submitButton->show(); - cancelButton->show(); - - loadButton->setEnabled(false); - saveButton->setEnabled(false); - break; - - case NavigationMode: - - if (contacts.isEmpty()) { - nameLine->clear(); - addressText->clear(); - } - - nameLine->setReadOnly(true); - addressText->setReadOnly(true); - addButton->setEnabled(true); - - int number = contacts.size(); - editButton->setEnabled(number >= 1); - removeButton->setEnabled(number >= 1); - findButton->setEnabled(number > 2); - nextButton->setEnabled(number > 1); - previousButton->setEnabled(number > 1); - - submitButton->hide(); - cancelButton->hide(); - - loadButton->setEnabled(true); - saveButton->setEnabled(number >= 1); - break; - } -} - -//! [saveToFile() function part1] -void AddressBook::saveToFile() -{ - QString fileName = QFileDialog::getSaveFileName(this, - tr("Save Address Book"), "", - tr("Address Book (*.abk);;All Files (*)")); - -//! [saveToFile() function part1] -//! [saveToFile() function part2] - if (fileName.isEmpty()) - return; - else { - QFile file(fileName); - if (!file.open(QIODevice::WriteOnly)) { - QMessageBox::information(this, tr("Unable to open file"), - file.errorString()); - return; - } - -//! [saveToFile() function part2] -//! [saveToFile() function part3] - QDataStream out(&file); - out.setVersion(QDataStream::Qt_4_5); - out << contacts; - } -} -//! [saveToFile() function part3] - -//! [loadFromFile() function part1] -void AddressBook::loadFromFile() -{ - QString fileName = QFileDialog::getOpenFileName(this, - tr("Open Address Book"), "", - tr("Address Book (*.abk);;All Files (*)")); -//! [loadFromFile() function part1] - -//! [loadFromFile() function part2] - if (fileName.isEmpty()) - return; - else { - - QFile file(fileName); - - if (!file.open(QIODevice::ReadOnly)) { - QMessageBox::information(this, tr("Unable to open file"), - file.errorString()); - return; - } - - QDataStream in(&file); - in.setVersion(QDataStream::Qt_4_5); - contacts.empty(); // empty existing contacts - in >> contacts; -//! [loadFromFile() function part2] - -//! [loadFromFile() function part3] - if (contacts.isEmpty()) { - QMessageBox::information(this, tr("No contacts in file"), - tr("The file you are attempting to open contains no contacts.")); - } else { - QMap<QString, QString>::iterator i = contacts.begin(); - nameLine->setText(i.key()); - addressText->setText(i.value()); - } - } - - updateInterface(NavigationMode); -} -//! [loadFromFile() function part3] diff --git a/examples/widgets/tutorials/addressbook-fr/part6/addressbook.h b/examples/widgets/tutorials/addressbook-fr/part6/addressbook.h deleted file mode 100644 index ce2691ccad..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part6/addressbook.h +++ /dev/null @@ -1,103 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ADDRESSBOOK_H -#define ADDRESSBOOK_H - -#include <QWidget> -#include <QMap> -#include "finddialog.h" - -QT_BEGIN_NAMESPACE -class QPushButton; -class QLabel; -class QLineEdit; -class QTextEdit; -QT_END_NAMESPACE - - -class AddressBook : public QWidget -{ - Q_OBJECT - -public: - AddressBook(QWidget *parent = 0); - enum Mode { NavigationMode, AddingMode, EditingMode }; - -public slots: - void addContact(); - void editContact(); - void submitContact(); - void cancel(); - void removeContact(); - void findContact(); - void next(); - void previous(); -//! [save and load functions declaration] - void saveToFile(); - void loadFromFile(); -//! [save and load functions declaration] - -private: - void updateInterface(Mode mode); - - QPushButton *addButton; - QPushButton *editButton; - QPushButton *removeButton; - QPushButton *findButton; - QPushButton *submitButton; - QPushButton *cancelButton; - QPushButton *nextButton; - QPushButton *previousButton; -//! [save and load buttons declaration] - QPushButton *loadButton; - QPushButton *saveButton; -//! [save and load buttons declaration] - QLineEdit *nameLine; - QTextEdit *addressText; - - QMap<QString, QString> contacts; - FindDialog *dialog; - QString oldName; - QString oldAddress; - Mode currentMode; -}; - -#endif diff --git a/examples/widgets/tutorials/addressbook-fr/part6/main.cpp b/examples/widgets/tutorials/addressbook-fr/part6/main.cpp deleted file mode 100644 index 70eabab255..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part6/main.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - AddressBook addressBook; - addressBook.show(); - - return app.exec(); -} diff --git a/examples/widgets/tutorials/addressbook-fr/part6/part6.pro b/examples/widgets/tutorials/addressbook-fr/part6/part6.pro deleted file mode 100644 index 4c7638fd70..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part6/part6.pro +++ /dev/null @@ -1,15 +0,0 @@ -QT += widgets - -SOURCES = addressbook.cpp \ - finddialog.cpp \ - main.cpp -HEADERS = addressbook.h \ - finddialog.h - -QMAKE_PROJECT_NAME = abfr_part6 - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook-fr/part6 -INSTALLS += target - -simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/tutorials/addressbook-fr/part7/addressbook.cpp b/examples/widgets/tutorials/addressbook-fr/part7/addressbook.cpp deleted file mode 100644 index a0780ae78a..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part7/addressbook.cpp +++ /dev/null @@ -1,446 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -AddressBook::AddressBook(QWidget *parent) - : QWidget(parent) -{ - QLabel *nameLabel = new QLabel(tr("Name:")); - nameLine = new QLineEdit; - nameLine->setReadOnly(true); - - QLabel *addressLabel = new QLabel(tr("Address:")); - addressText = new QTextEdit; - addressText->setReadOnly(true); - - addButton = new QPushButton(tr("&Add")); - - editButton = new QPushButton(tr("&Edit")); - editButton->setEnabled(false); - removeButton = new QPushButton(tr("&Remove")); - removeButton->setEnabled(false); - findButton = new QPushButton(tr("&Find")); - findButton->setEnabled(false); - submitButton = new QPushButton(tr("&Submit")); - submitButton->hide(); - cancelButton = new QPushButton(tr("&Cancel")); - cancelButton->hide(); - - nextButton = new QPushButton(tr("&Next")); - nextButton->setEnabled(false); - previousButton = new QPushButton(tr("&Previous")); - previousButton->setEnabled(false); - - loadButton = new QPushButton(tr("&Load...")); - loadButton->setToolTip(tr("Load contacts from a file")); - saveButton = new QPushButton(tr("Sa&ve...")); - saveButton->setToolTip(tr("Save contacts to a file")); - saveButton->setEnabled(false); - - exportButton = new QPushButton(tr("E&xport")); - exportButton->setToolTip(tr("Export as vCard")); - exportButton->setEnabled(false); - - dialog = new FindDialog; - - connect(addButton, SIGNAL(clicked()), this, SLOT(addContact())); - connect(submitButton, SIGNAL(clicked()), this, SLOT(submitContact())); - connect(editButton, SIGNAL(clicked()), this, SLOT(editContact())); - connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancel())); - connect(removeButton, SIGNAL(clicked()), this, SLOT(removeContact())); - connect(findButton, SIGNAL(clicked()), this, SLOT(findContact())); - connect(nextButton, SIGNAL(clicked()), this, SLOT(next())); - connect(previousButton, SIGNAL(clicked()), this, SLOT(previous())); - connect(loadButton, SIGNAL(clicked()), this, SLOT(loadFromFile())); - connect(saveButton, SIGNAL(clicked()), this, SLOT(saveToFile())); - connect(exportButton, SIGNAL(clicked()), this, SLOT(exportAsVCard())); - - QVBoxLayout *buttonLayout1 = new QVBoxLayout; - buttonLayout1->addWidget(addButton); - buttonLayout1->addWidget(editButton); - buttonLayout1->addWidget(removeButton); - buttonLayout1->addWidget(findButton); - buttonLayout1->addWidget(submitButton); - buttonLayout1->addWidget(cancelButton); - buttonLayout1->addWidget(loadButton); - buttonLayout1->addWidget(saveButton); - buttonLayout1->addWidget(exportButton); - buttonLayout1->addStretch(); - - QHBoxLayout *buttonLayout2 = new QHBoxLayout; - buttonLayout2->addWidget(previousButton); - buttonLayout2->addWidget(nextButton); - - QGridLayout *mainLayout = new QGridLayout; - mainLayout->addWidget(nameLabel, 0, 0); - mainLayout->addWidget(nameLine, 0, 1); - mainLayout->addWidget(addressLabel, 1, 0, Qt::AlignTop); - mainLayout->addWidget(addressText, 1, 1); - mainLayout->addLayout(buttonLayout1, 1, 2); - mainLayout->addLayout(buttonLayout2, 2, 1); - - setLayout(mainLayout); - setWindowTitle(tr("Simple Address Book")); -} - -void AddressBook::addContact() -{ - oldName = nameLine->text(); - oldAddress = addressText->toPlainText(); - - nameLine->clear(); - addressText->clear(); - - updateInterface(AddingMode); -} - -void AddressBook::editContact() -{ - oldName = nameLine->text(); - oldAddress = addressText->toPlainText(); - - updateInterface(EditingMode); -} - -void AddressBook::submitContact() -{ - QString name = nameLine->text(); - QString address = addressText->toPlainText(); - - if (name.isEmpty() || address.isEmpty()) { - QMessageBox::information(this, tr("Empty Field"), - tr("Please enter a name and address.")); - return; - } - - if (currentMode == AddingMode) { - - if (!contacts.contains(name)) { - contacts.insert(name, address); - QMessageBox::information(this, tr("Add Successful"), - tr("\"%1\" has been added to your address book.").arg(name)); - } else { - QMessageBox::information(this, tr("Add Unsuccessful"), - tr("Sorry, \"%1\" is already in your address book.").arg(name)); - } - } else if (currentMode == EditingMode) { - - if (oldName != name) { - if (!contacts.contains(name)) { - QMessageBox::information(this, tr("Edit Successful"), - tr("\"%1\" has been edited in your address book.").arg(oldName)); - contacts.remove(oldName); - contacts.insert(name, address); - } else { - QMessageBox::information(this, tr("Edit Unsuccessful"), - tr("Sorry, \"%1\" is already in your address book.").arg(name)); - } - } else if (oldAddress != address) { - QMessageBox::information(this, tr("Edit Successful"), - tr("\"%1\" has been edited in your address book.").arg(name)); - contacts[name] = address; - } - } - - updateInterface(NavigationMode); -} - -void AddressBook::cancel() -{ - nameLine->setText(oldName); - addressText->setText(oldAddress); - updateInterface(NavigationMode); -} - -void AddressBook::removeContact() -{ - QString name = nameLine->text(); - QString address = addressText->toPlainText(); - - if (contacts.contains(name)) { - - int button = QMessageBox::question(this, - tr("Confirm Remove"), - tr("Are you sure you want to remove \"%1\"?").arg(name), - QMessageBox::Yes | QMessageBox::No); - - if (button == QMessageBox::Yes) { - - previous(); - contacts.remove(name); - - QMessageBox::information(this, tr("Remove Successful"), - tr("\"%1\" has been removed from your address book.").arg(name)); - } - } - - updateInterface(NavigationMode); -} - -void AddressBook::next() -{ - QString name = nameLine->text(); - QMap<QString, QString>::iterator i = contacts.find(name); - - if (i != contacts.end()) - i++; - - if (i == contacts.end()) - i = contacts.begin(); - - nameLine->setText(i.key()); - addressText->setText(i.value()); -} - -void AddressBook::previous() -{ - QString name = nameLine->text(); - QMap<QString, QString>::iterator i = contacts.find(name); - - if (i == contacts.end()) { - nameLine->clear(); - addressText->clear(); - return; - } - - if (i == contacts.begin()) - i = contacts.end(); - - i--; - nameLine->setText(i.key()); - addressText->setText(i.value()); -} - -void AddressBook::findContact() -{ - dialog->show(); - - if (dialog->exec() == 1) { - QString contactName = dialog->getFindText(); - - if (contacts.contains(contactName)) { - nameLine->setText(contactName); - addressText->setText(contacts.value(contactName)); - } else { - QMessageBox::information(this, tr("Contact Not Found"), - tr("Sorry, \"%1\" is not in your address book.").arg(contactName)); - return; - } - } - - updateInterface(NavigationMode); -} -void AddressBook::updateInterface(Mode mode) -{ - currentMode = mode; - - switch (currentMode) { - - case AddingMode: - case EditingMode: - - nameLine->setReadOnly(false); - nameLine->setFocus(Qt::OtherFocusReason); - addressText->setReadOnly(false); - - addButton->setEnabled(false); - editButton->setEnabled(false); - removeButton->setEnabled(false); - - nextButton->setEnabled(false); - previousButton->setEnabled(false); - - submitButton->show(); - cancelButton->show(); - - loadButton->setEnabled(false); - saveButton->setEnabled(false); - exportButton->setEnabled(false); - break; - - case NavigationMode: - - if (contacts.isEmpty()) { - nameLine->clear(); - addressText->clear(); - } - - nameLine->setReadOnly(true); - addressText->setReadOnly(true); - addButton->setEnabled(true); - - int number = contacts.size(); - editButton->setEnabled(number >= 1); - removeButton->setEnabled(number >= 1); - findButton->setEnabled(number > 2); - nextButton->setEnabled(number > 1); - previousButton->setEnabled(number > 1); - - submitButton->hide(); - cancelButton->hide(); - - exportButton->setEnabled(number >= 1); - - loadButton->setEnabled(true); - saveButton->setEnabled(number >= 1); - break; - } -} - -void AddressBook::saveToFile() -{ - QString fileName = QFileDialog::getSaveFileName(this, - tr("Save Address Book"), "", - tr("Address Book (*.abk);;All Files (*)")); - - if (fileName.isEmpty()) - return; - else { - QFile file(fileName); - - if (!file.open(QIODevice::WriteOnly)) { - QMessageBox::information(this, tr("Unable to open file"), - file.errorString()); - return; - } - - QDataStream out(&file); - out.setVersion(QDataStream::Qt_4_3); - out << contacts; - } - - updateInterface(NavigationMode); -} - -void AddressBook::loadFromFile() -{ - QString fileName = QFileDialog::getOpenFileName(this, - tr("Open Address Book"), "", - tr("Address Book (*.abk);;All Files (*)")); - - if (fileName.isEmpty()) - return; - else { - QFile file(fileName); - - if (!file.open(QIODevice::ReadOnly)) { - QMessageBox::information(this, tr("Unable to open file"), - file.errorString()); - return; - } - - QDataStream in(&file); - in.setVersion(QDataStream::Qt_4_3); - contacts.empty(); // empty existing contacts - in >> contacts; - - QMap<QString, QString>::iterator i = contacts.begin(); - nameLine->setText(i.key()); - addressText->setText(i.value()); - } - - updateInterface(NavigationMode); -} - -//! [export function part1] -void AddressBook::exportAsVCard() -{ - QString name = nameLine->text(); - QString address = addressText->toPlainText(); - QString firstName; - QString lastName; - QStringList nameList; - - int index = name.indexOf(" "); - - if (index != -1) { - nameList = name.split(QRegExp("\\s+"), QString::SkipEmptyParts); - firstName = nameList.first(); - lastName = nameList.last(); - } else { - firstName = name; - lastName = ""; - } - - QString fileName = QFileDialog::getSaveFileName(this, - tr("Export Contact"), "", - tr("vCard Files (*.vcf);;All Files (*)")); - - if (fileName.isEmpty()) - return; - - QFile file(fileName); -//! [export function part1] - -//! [export function part2] - if (!file.open(QIODevice::WriteOnly)) { - QMessageBox::information(this, tr("Unable to open file"), - file.errorString()); - return; - } - - QTextStream out(&file); -//! [export function part2] - -//! [export function part3] - out << "BEGIN:VCARD" << "\n"; - out << "VERSION:2.1" << "\n"; - out << "N:" << lastName << ";" << firstName << "\n"; - - if (!nameList.isEmpty()) - out << "FN:" << nameList.join(' ') << "\n"; - else - out << "FN:" << firstName << "\n"; -//! [export function part3] - -//! [export function part4] - address.replace(";", "\\;", Qt::CaseInsensitive); - address.replace("\n", ";", Qt::CaseInsensitive); - address.replace(",", " ", Qt::CaseInsensitive); - - 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)); -} -//! [export function part4] diff --git a/examples/widgets/tutorials/addressbook-fr/part7/addressbook.h b/examples/widgets/tutorials/addressbook-fr/part7/addressbook.h deleted file mode 100644 index d672c7a85b..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part7/addressbook.h +++ /dev/null @@ -1,105 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ADDRESSBOOK_H -#define ADDRESSBOOK_H - -#include <QWidget> -#include <QMap> -#include "finddialog.h" - -QT_BEGIN_NAMESPACE -class QPushButton; -class QLabel; -class QLineEdit; -class QTextEdit; -QT_END_NAMESPACE - - -class AddressBook : public QWidget -{ - Q_OBJECT - -public: - AddressBook(QWidget *parent = 0); - enum Mode { NavigationMode, AddingMode, EditingMode }; - -public slots: - void addContact(); - void editContact(); - void submitContact(); - void cancel(); - void removeContact(); - void findContact(); - void next(); - void previous(); - void saveToFile(); - void loadFromFile(); -//! [exportAsVCard() declaration] - void exportAsVCard(); -//! [exportAsVCard() declaration] - -private: - void updateInterface(Mode mode); - - QPushButton *addButton; - QPushButton *editButton; - QPushButton *removeButton; - QPushButton *findButton; - QPushButton *submitButton; - QPushButton *cancelButton; - QPushButton *nextButton; - QPushButton *previousButton; - QPushButton *loadButton; - QPushButton *saveButton; -//! [exportButton declaration] - QPushButton *exportButton; -//! [exportButton declaration] - QLineEdit *nameLine; - QTextEdit *addressText; - - QMap<QString, QString> contacts; - FindDialog *dialog; - QString oldName; - QString oldAddress; - Mode currentMode; -}; - -#endif diff --git a/examples/widgets/tutorials/addressbook-fr/part7/finddialog.cpp b/examples/widgets/tutorials/addressbook-fr/part7/finddialog.cpp deleted file mode 100644 index a5efb678c8..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part7/finddialog.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "finddialog.h" - -FindDialog::FindDialog(QWidget *parent) - : QDialog(parent) -{ - QLabel *findLabel = new QLabel(tr("Enter the name of a contact:")); - lineEdit = new QLineEdit; - - findButton = new QPushButton(tr("&Find")); - findText = ""; - - QHBoxLayout *layout = new QHBoxLayout; - layout->addWidget(findLabel); - layout->addWidget(lineEdit); - layout->addWidget(findButton); - - setLayout(layout); - setWindowTitle(tr("Find a Contact")); - connect(findButton, SIGNAL(clicked()), this, SLOT(findClicked())); - connect(findButton, SIGNAL(clicked()), this, SLOT(accept())); -} - -void FindDialog::findClicked() -{ - QString text = lineEdit->text(); - - if (text.isEmpty()) { - QMessageBox::information(this, tr("Empty Field"), - tr("Please enter a name.")); - return; - } else { - findText = text; - lineEdit->clear(); - hide(); - } -} - -QString FindDialog::getFindText() -{ - return findText; -} diff --git a/examples/widgets/tutorials/addressbook-fr/part7/main.cpp b/examples/widgets/tutorials/addressbook-fr/part7/main.cpp deleted file mode 100644 index 70eabab255..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part7/main.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). -** Contact: http://www.qt-project.org/legal -** -** 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 Digia Plc and its Subsidiary(-ies) nor the names -** of its contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include <QtWidgets> -#include "addressbook.h" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - AddressBook addressBook; - addressBook.show(); - - return app.exec(); -} diff --git a/examples/widgets/tutorials/addressbook-fr/part7/part7.pro b/examples/widgets/tutorials/addressbook-fr/part7/part7.pro deleted file mode 100644 index 6f56489979..0000000000 --- a/examples/widgets/tutorials/addressbook-fr/part7/part7.pro +++ /dev/null @@ -1,15 +0,0 @@ -QT += widgets - -SOURCES = addressbook.cpp \ - finddialog.cpp \ - main.cpp -HEADERS = addressbook.h \ - finddialog.h - -QMAKE_PROJECT_NAME = abfr_part7 - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/widgets/tutorials/addressbook-fr/part7 -INSTALLS += target - -simulator: warning(This example might not fully work on Simulator platform) diff --git a/examples/widgets/tutorials/tutorials.pro b/examples/widgets/tutorials/tutorials.pro index cb57002082..cf94830551 100644 --- a/examples/widgets/tutorials/tutorials.pro +++ b/examples/widgets/tutorials/tutorials.pro @@ -1,2 +1,2 @@ TEMPLATE = subdirs -SUBDIRS += addressbook-fr threads addressbook widgets modelview gettingStarted +SUBDIRS += threads addressbook widgets modelview gettingStarted diff --git a/examples/widgets/widgets.pro b/examples/widgets/widgets.pro index 726494ffd6..14acebc33f 100644 --- a/examples/widgets/widgets.pro +++ b/examples/widgets/widgets.pro @@ -19,8 +19,11 @@ SUBDIRS = \ statemachine \ tools \ tutorials \ - widgets \ - windowcontainer + widgets + +contains(QT_CONFIG, opengl(es1|es2)?) { + SUBDIRS += windowcontainer +} contains(DEFINES, QT_NO_CURSOR): SUBDIRS -= mainwindows contains(DEFINES, QT_NO_DRAGANDDROP): SUBDIRS -= draganddrop diff --git a/mkspecs/android-g++/qmake.conf b/mkspecs/android-g++/qmake.conf index 0afea12e60..8c0e8c91f6 100644 --- a/mkspecs/android-g++/qmake.conf +++ b/mkspecs/android-g++/qmake.conf @@ -102,20 +102,18 @@ QMAKE_CFLAGS_WARN_ON = -Wall -Wno-psabi -W QMAKE_CFLAGS_WARN_OFF = -Wno-psabi equals(ANDROID_TARGET_ARCH, x86) { QMAKE_CFLAGS_RELEASE = -O2 - QMAKE_CFLAGS_RELEASE_WITH_DEBUGINFO = -g -O2 - QMAKE_CFLAGS_DEBUG = -g + QMAKE_CFLAGS_RELEASE_WITH_DEBUGINFO = -g -gdwarf-2 -O2 + QMAKE_CFLAGS_DEBUG = -g -gdwarf-2 } else: equals(ANDROID_TARGET_ARCH, mips) { QMAKE_CFLAGS_RELEASE = -O2 - QMAKE_CFLAGS_RELEASE_WITH_DEBUGINFO = -g -O2 - QMAKE_CFLAGS_DEBUG = -g -fno-omit-frame-pointer + QMAKE_CFLAGS_RELEASE_WITH_DEBUGINFO = -g -gdwarf-2 -O2 + QMAKE_CFLAGS_DEBUG = -g -gdwarf-2 -fno-omit-frame-pointer } else { # arm - QMAKE_CFLAGS_RELEASE = -Os -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 - QMAKE_CFLAGS_RELEASE_WITH_DEBUGINFO = -g -Os -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 - equals(ANDROID_TARGET_ARCH, armeabi-v7a) { - QMAKE_CFLAGS_RELEASE += -mthumb - QMAKE_CFLAGS_RELEASE_WITH_DEBUGINFO += -mthumb - } - QMAKE_CFLAGS_DEBUG = -g -marm -O0 -fno-omit-frame-pointer + QMAKE_CFLAGS_RELEASE = -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 + QMAKE_CFLAGS_RELEASE_WITH_DEBUGINFO = -g -gdwarf-2 -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 + QMAKE_CFLAGS_DEBUG = -g -gdwarf-2 -marm -O0 -fno-omit-frame-pointer + equals(ANDROID_TARGET_ARCH, armeabi): equals(NDK_TOOLCHAIN_VERSION, 4.8): \ + DEFINES += QT_OS_ANDROID_GCC_48_WORKAROUND } QMAKE_CFLAGS_SHLIB = -fPIC diff --git a/mkspecs/features/create_cmake.prf b/mkspecs/features/create_cmake.prf index 2dcb8da063..59c3fafac3 100644 --- a/mkspecs/features/create_cmake.prf +++ b/mkspecs/features/create_cmake.prf @@ -11,12 +11,6 @@ load(cmake_functions) -CMAKE_MODULE_NAME = $$cmakeModuleName($${MODULE}) - -CMAKE_MODULE_DEPS = $$cmakeModuleList($$sort_depends(QT.$${MODULE}.depends, QT.)) -CMAKE_PARTIAL_MODULE_DEPS = $$replace(CMAKE_MODULE_DEPS, ";", ";Qt5::") -!isEmpty(CMAKE_PARTIAL_MODULE_DEPS):CMAKE_QT5_MODULE_DEPS = "Qt5::$${CMAKE_PARTIAL_MODULE_DEPS}" - # Several distros (ArchLinux, Fedora) have in the past installed libraries # in /lib(64)?, but are now moving to install libraries in /usr/lib(64)?/. # The /lib paths are made symlinks to the /usr/lib paths. If someone searching @@ -68,10 +62,37 @@ contains(CMAKE_BIN_DIR, "^\\.\\./.*") { static|staticlib:CMAKE_STATIC_TYPE = true +CMAKE_DEBUG_TYPE = +CMAKE_RELEASE_TYPE = + +# Requirements: +# * If Qt is configured with -debug, we're creating debug libraries and not +# release libraries, regardless of whether we're on a platform where +# debug_and_release is true. +# * If Qt is configured with -release, we're creating release libraries and not +# debug libraries, regardless of whether we're on a platform where +# debug_and_release is true. +# * If Qt is configured with neither -debug nor -release, and we are on a +# platform where debug_and_release is true, we're creating both +# debug and release libraries. +# * If Qt is configured with -debug on a platform where debug_and_release is +# true, and 'make release' is subsequently invoked, CMake is only aware of +# the debug libraries at build time. + +equals(QMAKE_HOST.os, Windows): CMAKE_BIN_SUFFIX = ".exe" +if(build_all|CONFIG(debug, debug|release)): CMAKE_DEBUG_TYPE = debug +if(build_all|CONFIG(release, debug|release)): CMAKE_RELEASE_TYPE = release + unix:contains(QT_CONFIG, reduce_relocations):CMAKE_ADD_FPIE_FLAGS = "true" CMAKE_MKSPEC = $$[QMAKE_XSPEC] +CMAKE_MODULE_NAME = $$cmakeModuleName($${MODULE}) + +CMAKE_MODULE_DEPS = $$cmakeModuleList($$sort_depends(QT.$${MODULE}.depends, QT.)) +CMAKE_PARTIAL_MODULE_DEPS = $$replace(CMAKE_MODULE_DEPS, ";", ";Qt5::") +!isEmpty(CMAKE_PARTIAL_MODULE_DEPS):CMAKE_QT5_MODULE_DEPS = "Qt5::$${CMAKE_PARTIAL_MODULE_DEPS}" + CMAKE_QT_STEM = Qt$$eval(QT.$${MODULE}.MAJOR_VERSION)$${CMAKE_MODULE_NAME}$${QT_LIBINFIX} mac { @@ -142,27 +163,6 @@ mac { } } -CMAKE_DEBUG_TYPE = -CMAKE_RELEASE_TYPE = - -# Requirements: -# * If Qt is configured with -debug, we're creating debug libraries and not -# release libraries, regardless of whether we're on a platform where -# debug_and_release is true. -# * If Qt is configured with -release, we're creating release libraries and not -# debug libraries, regardless of whether we're on a platform where -# debug_and_release is true. -# * If Qt is configured with neither -debug nor -release, and we are on a -# platform where debug_and_release is true, we're creating both -# debug and release libraries. -# * If Qt is configured with -debug on a platform where debug_and_release is -# true, and 'make release' is subsequently invoked, CMake is only aware of -# the debug libraries at build time. - -equals(QMAKE_HOST.os, Windows): CMAKE_BIN_SUFFIX = ".exe" -if (build_all|CONFIG(debug, debug|release)):CMAKE_DEBUG_TYPE = debug -if (build_all|CONFIG(release, debug|release)):CMAKE_RELEASE_TYPE = release - INSTALLS += cmake_qt5_module_files cmake_config_file.input = $$PWD/data/cmake/Qt5BasicConfig.cmake.in diff --git a/mkspecs/features/data/cmake/Qt5BasicConfig.cmake.in b/mkspecs/features/data/cmake/Qt5BasicConfig.cmake.in index c4b58fe7d7..2ffb980156 100644 --- a/mkspecs/features/data/cmake/Qt5BasicConfig.cmake.in +++ b/mkspecs/features/data/cmake/Qt5BasicConfig.cmake.in @@ -57,11 +57,13 @@ macro(_populate_$${CMAKE_MODULE_NAME}_target_properties Configuration LIB_LOCATI !!ENDIF _qt5_$${CMAKE_MODULE_NAME}_check_file_exists(${imported_location}) set_target_properties(Qt5::$${CMAKE_MODULE_NAME} PROPERTIES - \"IMPORTED_LINK_INTERFACE_LIBRARIES_${Configuration}\" \"${_Qt5$${CMAKE_MODULE_NAME}_LIB_DEPENDENCIES}\" + \"INTERFACE_LINK_LIBRARIES\" \"${_Qt5$${CMAKE_MODULE_NAME}_LIB_DEPENDENCIES}\" \"IMPORTED_LOCATION_${Configuration}\" ${imported_location} !!IF !isEmpty(CMAKE_LIB_SONAME) \"IMPORTED_SONAME_${Configuration}\" \"$${CMAKE_LIB_SONAME}\" !!ENDIF + # For backward compatibility with CMake < 2.8.12 + \"IMPORTED_LINK_INTERFACE_LIBRARIES_${Configuration}\" \"${_Qt5$${CMAKE_MODULE_NAME}_LIB_DEPENDENCIES}\" ) !!IF !isEmpty(CMAKE_WINDOWS_BUILD) diff --git a/qmake/doc/snippets/code/doc_src_qmake-manual.pro b/qmake/doc/snippets/code/doc_src_qmake-manual.pro index aa3f7f3502..ff1edb878d 100644 --- a/qmake/doc/snippets/code/doc_src_qmake-manual.pro +++ b/qmake/doc/snippets/code/doc_src_qmake-manual.pro @@ -309,7 +309,8 @@ SOURCES = myclass.cpp \ #! [50] SUBDIRS = kernel \ - tools + tools \ + myapp #! [50] diff --git a/qmake/doc/src/qmake-manual.qdoc b/qmake/doc/src/qmake-manual.qdoc index 73538a7932..03eb3115f6 100644 --- a/qmake/doc/src/qmake-manual.qdoc +++ b/qmake/doc/src/qmake-manual.qdoc @@ -2227,20 +2227,24 @@ \target SUBDIRS \section1 SUBDIRS - This variable, when used with the \l{#TEMPLATE}{\c subdirs template} - Specifies the names of all subdirectories or project files that contain - parts of the project that need be built. Each subdirectory specified + This variable, when used with the \c subdirs \l{#TEMPLATE}{template} + specifies the names of all subdirectories or project files that contain + parts of the project that need to be built. Each subdirectory specified using this variable must contain its own project file. + It is recommended that the project file in each subdirectory has the same + base name as the subdirectory itself, because that makes it possible to omit + the file name. For example, if the subdirectory is called \c myapp, the + project file in that directory should be called \c myapp.pro. + + Alternatively, you can specify a relative path to a .pro file in any + directory. It is strongly recommended that you specify only paths in the + current project's parent directory or its subdirectories. + For example: \snippet code/doc_src_qmake-manual.pro 50 - It is essential that the project file in each subdirectory has the same - name as the subdirectory itself, so that qmake - can find it. For example, if the subdirectory is called \c myapp then the - project file in that directory should be called \c myapp.pro. - If you need to ensure that the subdirectories are built in the order in which they are specified, update the \l{#CONFIG}{CONFIG} variable to include the \c ordered option: diff --git a/src/corelib/Qt5CoreConfigExtras.cmake.in b/src/corelib/Qt5CoreConfigExtras.cmake.in index 36a54787b3..2d87783107 100644 --- a/src/corelib/Qt5CoreConfigExtras.cmake.in +++ b/src/corelib/Qt5CoreConfigExtras.cmake.in @@ -131,6 +131,11 @@ if (NOT TARGET Qt5::WinMain) get_target_property(_configs Qt5::Core IMPORTED_CONFIGURATIONS) foreach(_config ${_configs}) set_property(TARGET Qt5::Core APPEND PROPERTY + INTERFACE_LINK_LIBRARIES + $<$<AND:${_isExe},${_isWin32},${_isNotExcluded},${_isPolicyNEW}>:Qt5::WinMain> + ) + # For backward compatibility with CMake < 2.8.12 + set_property(TARGET Qt5::Core APPEND PROPERTY IMPORTED_LINK_INTERFACE_LIBRARIES_${_config} $<$<AND:${_isExe},${_isWin32},${_isNotExcluded},${_isPolicyNEW}>:Qt5::WinMain> ) diff --git a/src/corelib/Qt5CoreMacros.cmake b/src/corelib/Qt5CoreMacros.cmake index 6630885257..dca257f080 100644 --- a/src/corelib/Qt5CoreMacros.cmake +++ b/src/corelib/Qt5CoreMacros.cmake @@ -94,34 +94,45 @@ endmacro() # helper macro to set up a moc rule -macro(QT5_CREATE_MOC_COMMAND infile outfile moc_flags moc_options) - # For Windows, create a parameters file to work around command line length limit - if(WIN32) - # Pass the parameters in a file. Set the working directory to - # be that containing the parameters file and reference it by - # just the file name. This is necessary because the moc tool on - # MinGW builds does not seem to handle spaces in the path to the - # file given with the @ syntax. - get_filename_component(_moc_outfile_name "${outfile}" NAME) - get_filename_component(_moc_outfile_dir "${outfile}" PATH) - if(_moc_outfile_dir) - set(_moc_working_dir WORKING_DIRECTORY ${_moc_outfile_dir}) - endif() - set(_moc_parameters_file ${outfile}_parameters) - set(_moc_parameters ${moc_flags} ${moc_options} -o "${outfile}" "${infile}") - string(REPLACE ";" "\n" _moc_parameters "${_moc_parameters}") - file(WRITE ${_moc_parameters_file} "${_moc_parameters}") - add_custom_command(OUTPUT ${outfile} - COMMAND ${Qt5Core_MOC_EXECUTABLE} @${_moc_outfile_name}_parameters - DEPENDS ${infile} - ${_moc_working_dir} - VERBATIM) +macro(QT5_CREATE_MOC_COMMAND infile outfile moc_flags moc_options moc_target) + # Pass the parameters in a file. Set the working directory to + # be that containing the parameters file and reference it by + # just the file name. This is necessary because the moc tool on + # MinGW builds does not seem to handle spaces in the path to the + # file given with the @ syntax. + get_filename_component(_moc_outfile_name "${outfile}" NAME) + get_filename_component(_moc_outfile_dir "${outfile}" PATH) + if(_moc_outfile_dir) + set(_moc_working_dir WORKING_DIRECTORY ${_moc_outfile_dir}) + endif() + set (_moc_parameters_file ${outfile}_parameters) + set (_moc_parameters ${moc_flags} ${moc_options} -o "${outfile}" "${infile}") + string (REPLACE ";" "\n" _moc_parameters "${_moc_parameters}") + + if(moc_target) + set(targetincludes "$<TARGET_PROPERTY:${moc_target},INCLUDE_DIRECTORIES>") + set(targetdefines "$<TARGET_PROPERTY:${moc_target},COMPILE_DEFINITIONS>") + + set(targetincludes "$<$<BOOL:${targetincludes}>:-I$<JOIN:${targetincludes},\n-I>\n>") + set(targetdefines "$<$<BOOL:${targetdefines}>:-D$<JOIN:${targetdefines},\n-D>\n>") + + file (GENERATE + OUTPUT ${_moc_parameters_file} + CONTENT "${targetdefines}${targetincludes}${_moc_parameters}\n" + ) + + set(targetincludes) + set(targetdefines) else() - add_custom_command(OUTPUT ${outfile} - COMMAND ${Qt5Core_MOC_EXECUTABLE} - ARGS ${moc_flags} ${moc_options} -o ${outfile} ${infile} - DEPENDS ${infile} VERBATIM) + file(WRITE ${_moc_parameters_file} "${_moc_parameters}\n") endif() + + set(_moc_extra_parameters_file @${_moc_parameters_file}) + add_custom_command(OUTPUT ${outfile} + COMMAND ${Qt5Core_MOC_EXECUTABLE} ${_moc_extra_parameters_file} + DEPENDS ${infile} + ${_moc_working_dir} + VERBATIM) endmacro() @@ -133,7 +144,13 @@ function(QT5_GENERATE_MOC infile outfile ) if(NOT IS_ABSOLUTE "${outfile}") set(_outfile "${CMAKE_CURRENT_BINARY_DIR}/${outfile}") endif() - qt5_create_moc_command(${abs_infile} ${_outfile} "${moc_flags}" "") + if ("x${ARGV2}" STREQUAL "xTARGET") + if (CMAKE_VERSION VERSION_LESS 2.8.12) + message(FATAL_ERROR "The TARGET parameter to qt5_generate_moc is only available when using CMake 2.8.12 or later.") + endif() + set(moc_target ${ARGV3}) + endif() + qt5_create_moc_command(${abs_infile} ${_outfile} "${moc_flags}" "" "${moc_target}") set_source_files_properties(${outfile} PROPERTIES SKIP_AUTOMOC TRUE) # dont run automoc on this file endfunction() @@ -145,17 +162,22 @@ function(QT5_WRAP_CPP outfiles ) qt5_get_moc_flags(moc_flags) set(options) - set(oneValueArgs) + set(oneValueArgs TARGET) set(multiValueArgs OPTIONS) cmake_parse_arguments(_WRAP_CPP "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) set(moc_files ${_WRAP_CPP_UNPARSED_ARGUMENTS}) set(moc_options ${_WRAP_CPP_OPTIONS}) + set(moc_target ${_WRAP_CPP_TARGET}) + + if (moc_target AND CMAKE_VERSION VERSION_LESS 2.8.12) + message(FATAL_ERROR "The TARGET parameter to qt5_wrap_cpp is only available when using CMake 2.8.12 or later.") + endif() foreach(it ${moc_files}) get_filename_component(it ${it} ABSOLUTE) qt5_make_output_file(${it} moc_ cpp outfile) - qt5_create_moc_command(${it} ${outfile} "${moc_flags}" "${moc_options}") + qt5_create_moc_command(${it} ${outfile} "${moc_flags}" "${moc_options}" "${moc_target}") list(APPEND ${outfiles} ${outfile}) endforeach() set(${outfiles} ${${outfiles}} PARENT_SCOPE) diff --git a/src/corelib/doc/qtcore.qdocconf b/src/corelib/doc/qtcore.qdocconf index 7a3e20aa89..fdd46995c5 100644 --- a/src/corelib/doc/qtcore.qdocconf +++ b/src/corelib/doc/qtcore.qdocconf @@ -36,7 +36,8 @@ exampledirs += \ ../ \ snippets \ ../../../examples/threads/ \ - ../../../examples/tools/ + ../../../examples/tools/ \ + ../../../examples/json/ imagedirs += images diff --git a/src/corelib/doc/src/datastreamformat.qdoc b/src/corelib/doc/src/datastreamformat.qdoc index 99a0a077cd..b6efe6aa33 100644 --- a/src/corelib/doc/src/datastreamformat.qdoc +++ b/src/corelib/doc/src/datastreamformat.qdoc @@ -369,4 +369,6 @@ \li The items (T) \endlist \endtable + + \sa {JSON Support in Qt} */ diff --git a/src/corelib/doc/src/json.qdoc b/src/corelib/doc/src/json.qdoc index 89e1bcac34..5bffe98ae5 100644 --- a/src/corelib/doc/src/json.qdoc +++ b/src/corelib/doc/src/json.qdoc @@ -99,6 +99,8 @@ A valid JSON document is either an array or an object, so a document always starts with a square or curly bracket. + \sa {JSON Save Game Example} + \section1 The JSON Classes diff --git a/src/corelib/doc/src/objectmodel/properties.qdoc b/src/corelib/doc/src/objectmodel/properties.qdoc index d1690c5908..70f0b88e06 100644 --- a/src/corelib/doc/src/objectmodel/properties.qdoc +++ b/src/corelib/doc/src/objectmodel/properties.qdoc @@ -67,7 +67,7 @@ \li A \c READ accessor function is required if no \c MEMBER variable was specified. It is for reading the property value. Ideally, a const function is used for this purpose, and it must return either the property's type or a - pointer or reference to that type. e.g., QWidget::focus is a read-only + const reference to that type. e.g., QWidget::focus is a read-only property with \c READ function, QWidget::hasFocus(). \li A \c WRITE accessor function is optional. It is for setting the diff --git a/src/corelib/global/qglobal.cpp b/src/corelib/global/qglobal.cpp index 4ee4235278..9656f4b68a 100644 --- a/src/corelib/global/qglobal.cpp +++ b/src/corelib/global/qglobal.cpp @@ -1168,6 +1168,13 @@ bool qSharedBuild() Q_DECL_NOTHROW */ /*! + \macro Q_OS_ANDROID + \relates <QtGlobal> + + Defined on Android. +*/ + +/*! \macro Q_OS_FREEBSD \relates <QtGlobal> diff --git a/src/corelib/global/qglobal.h b/src/corelib/global/qglobal.h index 41f21bb0dd..e72ea792dd 100644 --- a/src/corelib/global/qglobal.h +++ b/src/corelib/global/qglobal.h @@ -206,11 +206,7 @@ typedef quint64 qulonglong; QT_BEGIN_INCLUDE_NAMESPACE typedef unsigned char uchar; typedef unsigned short ushort; -#if defined(Q_QDOC) || !defined(Q_OS_ANDROID) typedef unsigned int uint; -#else -# include <sys/types.h> -#endif typedef unsigned long ulong; QT_END_INCLUDE_NAMESPACE diff --git a/src/corelib/json/qjsonarray.cpp b/src/corelib/json/qjsonarray.cpp index fb8d2e83ff..8dd7f6092f 100644 --- a/src/corelib/json/qjsonarray.cpp +++ b/src/corelib/json/qjsonarray.cpp @@ -71,6 +71,8 @@ QT_BEGIN_NAMESPACE it has been created from as long as it is not being modified. You can convert the array to and from text based JSON through QJsonDocument. + + \sa {JSON Support in Qt}, {JSON Save Game Example} */ /*! diff --git a/src/corelib/json/qjsondocument.cpp b/src/corelib/json/qjsondocument.cpp index bdb46528d3..05d57e2ab9 100644 --- a/src/corelib/json/qjsondocument.cpp +++ b/src/corelib/json/qjsondocument.cpp @@ -76,6 +76,8 @@ QT_BEGIN_NAMESPACE A document can also be created from a stored binary representation using fromBinaryData() or fromRawData(). + + \sa {JSON Support in Qt}, {JSON Save Game Example} */ /*! diff --git a/src/corelib/json/qjsonobject.cpp b/src/corelib/json/qjsonobject.cpp index 43336de2e7..362d01384e 100644 --- a/src/corelib/json/qjsonobject.cpp +++ b/src/corelib/json/qjsonobject.cpp @@ -70,6 +70,8 @@ QT_BEGIN_NAMESPACE it has been created from as long as it is not being modified. You can convert the object to and from text based JSON through QJsonDocument. + + \sa {JSON Support in Qt}, {JSON Save Game Example} */ /*! @@ -604,7 +606,7 @@ QJsonObject::const_iterator QJsonObject::constFind(const QString &key) const Multiple iterators can be used on the same object. Existing iterators will however become dangling once the object gets modified. - \sa QJsonObject::const_iterator + \sa QJsonObject::const_iterator, {JSON Support in Qt}, {JSON Save Game Example} */ /*! \typedef QJsonObject::iterator::difference_type @@ -799,7 +801,7 @@ QJsonObject::const_iterator QJsonObject::constFind(const QString &key) const Multiple iterators can be used on the same object. Existing iterators will however become dangling if the object gets modified. - \sa QJsonObject::iterator + \sa QJsonObject::iterator, {JSON Support in Qt}, {JSON Save Game Example} */ /*! \typedef QJsonObject::const_iterator::difference_type diff --git a/src/corelib/json/qjsonparser.cpp b/src/corelib/json/qjsonparser.cpp index b151af7955..8721f06064 100644 --- a/src/corelib/json/qjsonparser.cpp +++ b/src/corelib/json/qjsonparser.cpp @@ -86,6 +86,8 @@ QT_BEGIN_NAMESPACE \since 5.0 \brief The QJsonParseError class is used to report errors during JSON parsing. + + \sa {JSON Support in Qt}, {JSON Save Game Example} */ /*! diff --git a/src/corelib/json/qjsonvalue.cpp b/src/corelib/json/qjsonvalue.cpp index ef9f057d77..d0634602f3 100644 --- a/src/corelib/json/qjsonvalue.cpp +++ b/src/corelib/json/qjsonvalue.cpp @@ -81,6 +81,8 @@ QT_BEGIN_NAMESPACE Values are strictly typed internally and contrary to QVariant will not attempt to do any implicit type conversions. This implies that converting to a type that is not stored in the value will return a default constructed return value. + + \sa {JSON Support in Qt}, {JSON Save Game Example} */ /*! diff --git a/src/corelib/tools/qbytearray.cpp b/src/corelib/tools/qbytearray.cpp index a2d3891f00..20d4339a19 100644 --- a/src/corelib/tools/qbytearray.cpp +++ b/src/corelib/tools/qbytearray.cpp @@ -646,6 +646,8 @@ static inline char qToLower(char c) store raw binary data, and when memory conservation is critical (e.g., with Qt for Embedded Linux). + The maximum array size of a QByteArray is under 2^30. + One way to initialize a QByteArray is simply to pass a \c{const char *} to its constructor. For example, the following code creates a byte array of size 5 containing the data "Hello": diff --git a/src/gui/kernel/qguiapplication.cpp b/src/gui/kernel/qguiapplication.cpp index 6be3b066d8..eed1c41bfa 100644 --- a/src/gui/kernel/qguiapplication.cpp +++ b/src/gui/kernel/qguiapplication.cpp @@ -1664,7 +1664,7 @@ void QGuiApplicationPrivate::processKeyEvent(QWindowSystemInterfacePrivate::KeyE ) { return; } - if (window->d_func()->blockedByModalWindow) { + if (window && window->d_func()->blockedByModalWindow) { // a modal window is blocking this window, don't allow key events through return; } diff --git a/src/gui/kernel/qwindow.cpp b/src/gui/kernel/qwindow.cpp index 9ef19715ed..490cf0c110 100644 --- a/src/gui/kernel/qwindow.cpp +++ b/src/gui/kernel/qwindow.cpp @@ -348,8 +348,9 @@ void QWindowPrivate::updateVisibility() void QWindowPrivate::setScreen(QScreen *newScreen, bool recreate) { Q_Q(QWindow); - if (newScreen != q->screen()) { - const bool shouldRecreate = recreate && platformWindow != 0; + if (newScreen != screen) { + const bool shouldRecreate = recreate && platformWindow != 0 + && !(screen && screen->virtualSiblings().contains(newScreen)); if (shouldRecreate) q->destroy(); if (screen) diff --git a/src/gui/opengl/qopenglfunctions_es2.h b/src/gui/opengl/qopenglfunctions_es2.h index 9c14567723..21ed6bec93 100644 --- a/src/gui/opengl/qopenglfunctions_es2.h +++ b/src/gui/opengl/qopenglfunctions_es2.h @@ -44,7 +44,7 @@ #include <QtCore/qglobal.h> -#if defined(QT_OPENGL_ES_2) +#if defined(QT_OPENGL_ES_2) || defined(Q_QDOC) #include <QtGui/QOpenGLVersionFunctions> #include <QtGui/qopenglcontext.h> diff --git a/src/gui/painting/qbackingstore.cpp b/src/gui/painting/qbackingstore.cpp index edb5f66c5b..c1f7c6c738 100644 --- a/src/gui/painting/qbackingstore.cpp +++ b/src/gui/painting/qbackingstore.cpp @@ -97,6 +97,11 @@ void QBackingStore::flush(const QRegion ®ion, QWindow *win, const QPoint &off { if (!win) win = window(); + if (!win->handle()) { + qWarning() << "QBackingStore::flush() called for " + << win << " which does not have a handle."; + return; + } #ifdef QBACKINGSTORE_DEBUG if (win && win->isTopLevel() && !qt_window_private(win)->receivedExpose) { diff --git a/src/gui/text/qcssparser.cpp b/src/gui/text/qcssparser.cpp index 1264330873..b486ec05fa 100644 --- a/src/gui/text/qcssparser.cpp +++ b/src/gui/text/qcssparser.cpp @@ -583,7 +583,11 @@ bool ValueExtractor::extractBorder(int *borders, QBrush *colors, BorderStyle *st case BorderRightStyle: styles[RightEdge] = decl.styleValue(); break; case BorderStyles: decl.styleValues(styles); break; +#ifndef QT_OS_ANDROID_GCC_48_WORKAROUND case BorderTopLeftRadius: radii[0] = sizeValue(decl); break; +#else + case BorderTopLeftRadius: new(radii)QSize(sizeValue(decl)); break; +#endif case BorderTopRightRadius: radii[1] = sizeValue(decl); break; case BorderBottomLeftRadius: radii[2] = sizeValue(decl); break; case BorderBottomRightRadius: radii[3] = sizeValue(decl); break; diff --git a/src/gui/text/qdistancefield.cpp b/src/gui/text/qdistancefield.cpp index f4274a2c19..e584b66a25 100644 --- a/src/gui/text/qdistancefield.cpp +++ b/src/gui/text/qdistancefield.cpp @@ -487,15 +487,19 @@ static void drawPolygons(qint32 *bits, int width, int height, const QPoint *vert } } -static QImage makeDistanceField(int imgWidth, int imgHeight, const QPainterPath &path, int dfScale, int offs) +static void makeDistanceField(QDistanceFieldData *data, const QPainterPath &path, int dfScale, int offs) { - QImage image(imgWidth, imgHeight, QImage::Format_Indexed8); + if (!data || !data->data) + return; if (path.isEmpty()) { - image.fill(0); - return image; + memset(data->data, 0, data->nbytes); + return; } + int imgWidth = data->width; + int imgHeight = data->height; + QTransform transform; transform.translate(offs, offs); transform.scale(qreal(1) / dfScale, qreal(1) / dfScale); @@ -521,8 +525,8 @@ static QImage makeDistanceField(int imgWidth, int imgHeight, const QPainterPath QVarLengthArray<bool> isConvex; QVarLengthArray<bool> needsClipping; - drawPolygons(bits.data(), imgWidth, imgHeight, pathVertices.data(), indices, pathIndices.size(), - interiorColor); + drawPolygons(bits.data(), imgWidth, imgHeight, pathVertices.data(), + indices, pathIndices.size(), interiorColor); int index = 0; @@ -681,15 +685,11 @@ static QImage makeDistanceField(int imgWidth, int imgHeight, const QPainterPath } const qint32 *inLine = bits.data(); - uchar *outLine = image.bits(); - int padding = image.bytesPerLine() - image.width(); + uchar *outLine = data->data; for (int y = 0; y < imgHeight; ++y) { for (int x = 0; x < imgWidth; ++x, ++inLine, ++outLine) *outLine = uchar((0x7f80 - *inLine) >> 8); - outLine += padding; } - - return image; } static bool imageHasNarrowOutlines(const QImage &im) @@ -769,31 +769,96 @@ bool qt_fontHasNarrowOutlines(const QRawFont &f) QRawFont::PixelAntialiasing)); } -static QImage renderDistanceFieldPath(const QPainterPath &path, bool doubleResolution) + +QDistanceFieldData::QDistanceFieldData(const QDistanceFieldData &other) + : QSharedData(other) + , glyph(other.glyph) + , width(other.width) + , height(other.height) + , nbytes(other.nbytes) +{ + if (nbytes && other.data) + data = (uchar *)memcpy(malloc(nbytes), other.data, nbytes); + else + data = 0; +} + +QDistanceFieldData::~QDistanceFieldData() +{ + free(data); +} + +QDistanceFieldData *QDistanceFieldData::create(const QSize &size) +{ + QDistanceFieldData *data = new QDistanceFieldData; + + if (size.isValid()) { + data->width = size.width(); + data->height = size.height(); + // pixel data stored as a 1-byte alpha value + data->nbytes = data->width * data->height; // tightly packed + data->data = (uchar *)malloc(data->nbytes); + } + + return data; +} + +QDistanceFieldData *QDistanceFieldData::create(const QPainterPath &path, bool doubleResolution) { int dfMargin = QT_DISTANCEFIELD_RADIUS(doubleResolution) / QT_DISTANCEFIELD_SCALE(doubleResolution); int glyphWidth = qCeil(path.boundingRect().width() / QT_DISTANCEFIELD_SCALE(doubleResolution)) + dfMargin * 2; - QImage im = makeDistanceField(glyphWidth, - QT_DISTANCEFIELD_TILESIZE(doubleResolution), - path, - QT_DISTANCEFIELD_SCALE(doubleResolution), - QT_DISTANCEFIELD_RADIUS(doubleResolution) / QT_DISTANCEFIELD_SCALE(doubleResolution)); - return im; + QDistanceFieldData *data = create(QSize(glyphWidth, QT_DISTANCEFIELD_TILESIZE(doubleResolution))); + + makeDistanceField(data, + path, + QT_DISTANCEFIELD_SCALE(doubleResolution), + QT_DISTANCEFIELD_RADIUS(doubleResolution) / QT_DISTANCEFIELD_SCALE(doubleResolution)); + return data; } -QImage qt_renderDistanceFieldGlyph(QFontEngine *fe, glyph_t glyph, bool doubleResolution) + +QDistanceField::QDistanceField() + : d(new QDistanceFieldData) { - QFixedPoint position; - QPainterPath path; - fe->addGlyphsToPath(&glyph, &position, 1, &path, 0); - path.translate(-path.boundingRect().topLeft()); - path.setFillRule(Qt::WindingFill); +} - return renderDistanceFieldPath(path, doubleResolution); +QDistanceField::QDistanceField(int width, int height) + : d(QDistanceFieldData::create(QSize(width, height))) +{ } -QImage qt_renderDistanceFieldGlyph(const QRawFont &font, glyph_t glyph, bool doubleResolution) +QDistanceField::QDistanceField(const QDistanceField &other) +{ + d = other.d; +} + +QDistanceField::QDistanceField(const QRawFont &font, glyph_t glyph, bool doubleResolution) +{ + setGlyph(font, glyph, doubleResolution); +} + +QDistanceField::QDistanceField(QFontEngine *fontEngine, glyph_t glyph, bool doubleResolution) +{ + setGlyph(fontEngine, glyph, doubleResolution); +} + +QDistanceField::QDistanceField(QDistanceFieldData *data) + : d(data) +{ +} + +bool QDistanceField::isNull() const +{ + return !d->data; +} + +glyph_t QDistanceField::glyph() const +{ + return d->glyph; +} + +void QDistanceField::setGlyph(const QRawFont &font, glyph_t glyph, bool doubleResolution) { QRawFont renderFont = font; renderFont.setPixelSize(QT_DISTANCEFIELD_BASEFONTSIZE(doubleResolution) * QT_DISTANCEFIELD_SCALE(doubleResolution)); @@ -802,7 +867,158 @@ QImage qt_renderDistanceFieldGlyph(const QRawFont &font, glyph_t glyph, bool dou path.translate(-path.boundingRect().topLeft()); path.setFillRule(Qt::WindingFill); - return renderDistanceFieldPath(path, doubleResolution); + d = QDistanceFieldData::create(path, doubleResolution); + d->glyph = glyph; +} + +void QDistanceField::setGlyph(QFontEngine *fontEngine, glyph_t glyph, bool doubleResolution) +{ + QFixedPoint position; + QPainterPath path; + fontEngine->addGlyphsToPath(&glyph, &position, 1, &path, 0); + path.translate(-path.boundingRect().topLeft()); + path.setFillRule(Qt::WindingFill); + + d = QDistanceFieldData::create(path, doubleResolution); + d->glyph = glyph; +} + +int QDistanceField::width() const +{ + return d->width; +} + +int QDistanceField::height() const +{ + return d->height; +} + +QDistanceField QDistanceField::copy(const QRect &r) const +{ + if (isNull()) + return QDistanceField(); + + if (r.isNull()) + return QDistanceField(new QDistanceFieldData(*d)); + + int x = r.x(); + int y = r.y(); + int w = r.width(); + int h = r.height(); + + int dx = 0; + int dy = 0; + if (w <= 0 || h <= 0) + return QDistanceField(); + + QDistanceField df(w, h); + if (df.isNull()) + return df; + + if (x < 0 || y < 0 || x + w > d->width || y + h > d->height) { + memset(df.d->data, 0, df.d->nbytes); + if (x < 0) { + dx = -x; + x = 0; + } + if (y < 0) { + dy = -y; + y = 0; + } + } + + int pixels_to_copy = qMax(w - dx, 0); + if (x > d->width) + pixels_to_copy = 0; + else if (pixels_to_copy > d->width - x) + pixels_to_copy = d->width - x; + int lines_to_copy = qMax(h - dy, 0); + if (y > d->height) + lines_to_copy = 0; + else if (lines_to_copy > d->height - y) + lines_to_copy = d->height - y; + + const uchar *src = d->data + x + y * d->width; + uchar *dest = df.d->data + dx + dy * df.d->width; + for (int i = 0; i < lines_to_copy; ++i) { + memcpy(dest, src, pixels_to_copy); + src += d->width; + dest += df.d->width; + } + + df.d->glyph = d->glyph; + + return df; +} + +uchar *QDistanceField::bits() +{ + return d->data; +} + +const uchar *QDistanceField::bits() const +{ + return d->data; +} + +const uchar *QDistanceField::constBits() const +{ + return d->data; +} + +uchar *QDistanceField::scanLine(int i) +{ + if (isNull()) + return 0; + + Q_ASSERT(i >= 0 && i < d->height); + return d->data + i * d->width; +} + +const uchar *QDistanceField::scanLine(int i) const +{ + if (isNull()) + return 0; + + Q_ASSERT(i >= 0 && i < d->height); + return d->data + i * d->width; +} + +const uchar *QDistanceField::constScanLine(int i) const +{ + if (isNull()) + return 0; + + Q_ASSERT(i >= 0 && i < d->height); + return d->data + i * d->width; +} + +QImage QDistanceField::toImage(QImage::Format format) const +{ + if (isNull()) + return QImage(); + + QImage image(d->width, d->height, format == QImage::Format_Indexed8 ? + format : QImage::Format_ARGB32_Premultiplied); + if (image.isNull()) + return image; + + if (format == QImage::Format_Indexed8) { + for (int y = 0; y < d->height; ++y) + memcpy(image.scanLine(y), scanLine(y), d->width); + } else { + for (int y = 0; y < d->height; ++y) { + for (int x = 0; x < d->width; ++x) { + uint alpha = *(d->data + x + y * d->width); + image.setPixel(x, y, alpha << 24); + } + } + + if (image.format() != format) + image = image.convertToFormat(format); + } + + return image; } QT_END_NAMESPACE diff --git a/src/gui/text/qdistancefield_p.h b/src/gui/text/qdistancefield_p.h index f181aadd9d..d4c4f8f46d 100644 --- a/src/gui/text/qdistancefield_p.h +++ b/src/gui/text/qdistancefield_p.h @@ -55,6 +55,7 @@ #include <qrawfont.h> #include <private/qfontengine_p.h> +#include <QtCore/qshareddata.h> QT_BEGIN_NAMESPACE @@ -78,9 +79,69 @@ QT_BEGIN_NAMESPACE QT_DISTANCEFIELD_DEFAULT_RADIUS) bool Q_GUI_EXPORT qt_fontHasNarrowOutlines(const QRawFont &f); -QImage Q_GUI_EXPORT qt_renderDistanceFieldGlyph(const QRawFont &font, glyph_t glyph, bool doubleResolution); bool Q_GUI_EXPORT qt_fontHasNarrowOutlines(QFontEngine *fontEngine); -QImage Q_GUI_EXPORT qt_renderDistanceFieldGlyph(QFontEngine *fontEngine, glyph_t glyph, bool doubleResolution); + +class Q_GUI_EXPORT QDistanceFieldData : public QSharedData +{ +public: + QDistanceFieldData() : glyph(0), width(0), height(0), nbytes(0), data(0) {} + QDistanceFieldData(const QDistanceFieldData &other); + ~QDistanceFieldData(); + + static QDistanceFieldData *create(const QSize &size); + static QDistanceFieldData *create(const QPainterPath &path, bool doubleResolution); + + glyph_t glyph; + int width; + int height; + int nbytes; + uchar *data; +}; + +class Q_GUI_EXPORT QDistanceField +{ +public: + QDistanceField(); + QDistanceField(int width, int height); + QDistanceField(const QRawFont &font, glyph_t glyph, bool doubleResolution = false); + QDistanceField(QFontEngine *fontEngine, glyph_t glyph, bool doubleResolution = false); + QDistanceField(const QDistanceField &other); + + bool isNull() const; + + glyph_t glyph() const; + void setGlyph(const QRawFont &font, glyph_t glyph, bool doubleResolution = false); + void setGlyph(QFontEngine *fontEngine, glyph_t glyph, bool doubleResolution = false); + + int width() const; + int height() const; + + QDistanceField copy(const QRect &rect = QRect()) const; + inline QDistanceField copy(int x, int y, int w, int h) const + { return copy(QRect(x, y, w, h)); } + + uchar *bits(); + const uchar *bits() const; + const uchar *constBits() const; + + uchar *scanLine(int); + const uchar *scanLine(int) const; + const uchar *constScanLine(int) const; + + QImage toImage(QImage::Format format = QImage::Format_ARGB32_Premultiplied) const; + +private: + QDistanceField(QDistanceFieldData *data); + QSharedDataPointer<QDistanceFieldData> d; + + friend class QDistanceFieldData; +}; + + +inline QImage Q_GUI_EXPORT qt_renderDistanceFieldGlyph(const QRawFont &f, glyph_t g, bool d) +{ return QDistanceField(f, g, d).toImage(QImage::Format_Indexed8); } +inline QImage Q_GUI_EXPORT qt_renderDistanceFieldGlyph(QFontEngine *fe, glyph_t g, bool d) +{ return QDistanceField(fe, g, d).toImage(QImage::Format_Indexed8); } QT_END_NAMESPACE diff --git a/src/gui/text/qfontdatabase.cpp b/src/gui/text/qfontdatabase.cpp index 2e4f341e39..97ac604197 100644 --- a/src/gui/text/qfontdatabase.cpp +++ b/src/gui/text/qfontdatabase.cpp @@ -315,9 +315,6 @@ struct QtFontFamily QtFontFamily(const QString &n) : fixedPitch(false), -#if !defined(QWS) && defined(Q_OS_MAC) - fixedPitchComputed(false), -#endif name(n), count(0), foundries(0) , bogusWritingSystems(false) , askedForFallback(false) @@ -331,9 +328,6 @@ struct QtFontFamily } bool fixedPitch : 1; -#if !defined(QWS) && defined(Q_OS_MAC) - bool fixedPitchComputed : 1; -#endif QString name; QStringList aliases; @@ -349,18 +343,6 @@ struct QtFontFamily QtFontFoundry *foundry(const QString &f, bool = false); }; -#if !defined(QWS) && defined(Q_OS_MAC) -inline static void qt_mac_get_fixed_pitch(QtFontFamily *f) -{ - if(f && !f->fixedPitchComputed) { - QFontMetrics fm(f->name); - f->fixedPitch = fm.width(QLatin1Char('i')) == fm.width(QLatin1Char('m')); - f->fixedPitchComputed = true; - } -} -#endif - - QtFontFoundry *QtFontFamily::foundry(const QString &f, bool create) { if (f.isNull() && count == 1) @@ -824,9 +806,6 @@ unsigned int bestFoundry(int script, unsigned int score, int styleStrategy, EncodingMismatch = 0x0002 }; if (pitch != '*') { -#if !defined(QWS) && defined(Q_OS_MAC) - qt_mac_get_fixed_pitch(const_cast<QtFontFamily*>(family)); -#endif if ((pitch == 'm' && !family->fixedPitch) || (pitch == 'p' && family->fixedPitch)) this_score += PitchMismatch; @@ -1275,9 +1254,6 @@ bool QFontDatabase::isFixedPitch(const QString &family, QT_PREPEND_NAMESPACE(load)(familyName); QtFontFamily *f = d->family(familyName); -#if !defined(QWS) && defined(Q_OS_MAC) - qt_mac_get_fixed_pitch(f); -#endif return (f && f->fixedPitch); } diff --git a/src/network/kernel/qnetworkinterface_unix.cpp b/src/network/kernel/qnetworkinterface_unix.cpp index b090213861..01c082059f 100644 --- a/src/network/kernel/qnetworkinterface_unix.cpp +++ b/src/network/kernel/qnetworkinterface_unix.cpp @@ -312,38 +312,38 @@ QT_END_INCLUDE_NAMESPACE static QList<QNetworkInterfacePrivate *> createInterfaces(ifaddrs *rawList) { QList<QNetworkInterfacePrivate *> interfaces; + QSet<QString> seenInterfaces; + // on Linux, AF_PACKET addresses carry the hardware address and interface index; + // scan for them first (they're usually first, but we have no guarantee this + // will be the case forever) for (ifaddrs *ptr = rawList; ptr; ptr = ptr->ifa_next) { - if ( !ptr->ifa_addr ) - continue; - - // Get the interface index - int ifindex = if_nametoindex(ptr->ifa_name); + if (ptr->ifa_addr && ptr->ifa_addr->sa_family == AF_PACKET) { + sockaddr_ll *sll = (sockaddr_ll *)ptr->ifa_addr; + QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate; + interfaces << iface; + iface->index = sll->sll_ifindex; + iface->name = QString::fromLatin1(ptr->ifa_name); + iface->flags = convertFlags(ptr->ifa_flags); + iface->hardwareAddress = iface->makeHwAddress(sll->sll_halen, (uchar*)sll->sll_addr); - // on Linux we use AF_PACKET and sockaddr_ll to obtain hHwAddress - QList<QNetworkInterfacePrivate *>::Iterator if_it = interfaces.begin(); - for ( ; if_it != interfaces.end(); ++if_it) - if ((*if_it)->index == ifindex) { - // this one has been added already - if ( ptr->ifa_addr->sa_family == AF_PACKET - && (*if_it)->hardwareAddress.isEmpty()) { - sockaddr_ll *sll = (sockaddr_ll *)ptr->ifa_addr; - (*if_it)->hardwareAddress = (*if_it)->makeHwAddress(sll->sll_halen, (uchar*)sll->sll_addr); - } - break; - } - if ( if_it != interfaces.end() ) - continue; + seenInterfaces.insert(iface->name); + } + } - QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate; - interfaces << iface; - iface->index = ifindex; - iface->name = QString::fromLatin1(ptr->ifa_name); - iface->flags = convertFlags(ptr->ifa_flags); + // see if we missed anything: + // virtual interfaces with no HW address have no AF_PACKET + for (ifaddrs *ptr = rawList; ptr; ptr = ptr->ifa_next) { + if (ptr->ifa_addr && ptr->ifa_addr->sa_family != AF_PACKET) { + QString name = QString::fromLatin1(ptr->ifa_name); + if (seenInterfaces.contains(name)) + continue; - if ( ptr->ifa_addr->sa_family == AF_PACKET ) { - sockaddr_ll *sll = (sockaddr_ll *)ptr->ifa_addr; - iface->hardwareAddress = iface->makeHwAddress(sll->sll_halen, (uchar*)sll->sll_addr); + QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate; + interfaces << iface; + iface->name = name; + iface->flags = convertFlags(ptr->ifa_flags); + iface->index = if_nametoindex(ptr->ifa_name); } } @@ -423,11 +423,11 @@ static QList<QNetworkInterfacePrivate *> interfaceListing() interfaces = createInterfaces(interfaceListing); for (ifaddrs *ptr = interfaceListing; ptr; ptr = ptr->ifa_next) { // Get the interface index - int ifindex = if_nametoindex(ptr->ifa_name); + QString name = QString::fromLatin1(ptr->ifa_name); QNetworkInterfacePrivate *iface = 0; QList<QNetworkInterfacePrivate *>::Iterator if_it = interfaces.begin(); for ( ; if_it != interfaces.end(); ++if_it) - if ((*if_it)->index == ifindex) { + if ((*if_it)->name == name) { // found this interface already iface = *if_it; break; diff --git a/src/platformsupport/jniconvenience/qjnihelpers_p.h b/src/platformsupport/jniconvenience/qjnihelpers_p.h index fb44d156bd..437a0d039a 100644 --- a/src/platformsupport/jniconvenience/qjnihelpers_p.h +++ b/src/platformsupport/jniconvenience/qjnihelpers_p.h @@ -157,33 +157,39 @@ private: template <class T, class X> bool operator==(const QJNILocalRef<T> &ptr1, const QJNILocalRef<X> &ptr2) { - return ptr1.m_obj == ptr2.m_obj; + QAttachedJNIEnv env; + return env->IsSameObject(ptr1.m_obj, ptr2.m_obj); } template <class T, class X> bool operator!=(const QJNILocalRef<T> &ptr1, const QJNILocalRef<X> &ptr2) { - return ptr1.m_obj != ptr2.m_obj; + QAttachedJNIEnv env; + return !env->IsSameObject(ptr1.m_obj, ptr2.m_obj); } template <class T, class X> bool operator==(const QJNILocalRef<T> &ptr1, X ptr2) { - return ptr1.m_obj == ptr2; + QAttachedJNIEnv env; + return env->IsSameObject(ptr1.m_obj, ptr2); } template <class T, class X> bool operator==(T ptr1, const QJNILocalRef<X> &ptr2) { - return ptr1 == ptr2.m_obj; + QAttachedJNIEnv env; + return env->IsSameObject(ptr1, ptr2.m_obj); } template <class T, class X> bool operator!=(const QJNILocalRef<T> &ptr1, X ptr2) { - return !(ptr1 == ptr2); + QAttachedJNIEnv env; + return !env->IsSameObject(ptr1.m_obj, ptr2); } template <class T, class X> bool operator!=(const T *ptr1, const QJNILocalRef<X> &ptr2) { - return !(ptr2 == ptr1); + QAttachedJNIEnv env; + return !env->IsSameObject(ptr1, ptr2.m_obj); } QT_END_NAMESPACE diff --git a/src/platformsupport/jniconvenience/qjniobject.cpp b/src/platformsupport/jniconvenience/qjniobject.cpp index 515e82b2f0..ecf247aabf 100644 --- a/src/platformsupport/jniconvenience/qjniobject.cpp +++ b/src/platformsupport/jniconvenience/qjniobject.cpp @@ -57,6 +57,9 @@ static jclass getCachedClass(JNIEnv *env, const char *className) jclass c = env->FindClass(className); if (env->ExceptionCheck()) { c = 0; +#ifdef QT_DEBUG + env->ExceptionDescribe(); +#endif // QT_DEBUG env->ExceptionClear(); } if (c) @@ -88,6 +91,9 @@ static jmethodID getCachedMethodID(JNIEnv *env, if (env->ExceptionCheck()) { id = 0; +#ifdef QT_DEBUG + env->ExceptionDescribe(); +#endif // QT_DEBUG env->ExceptionClear(); } @@ -117,6 +123,9 @@ static jfieldID getCachedFieldID(JNIEnv *env, if (env->ExceptionCheck()) { id = 0; +#ifdef QT_DEBUG + env->ExceptionDescribe(); +#endif // QT_DEBUG env->ExceptionClear(); } @@ -127,7 +136,7 @@ static jfieldID getCachedFieldID(JNIEnv *env, return id; } -QJNIObject::QJNIObject(const char *className) +QJNIObjectPrivate::QJNIObjectPrivate(const char *className) : m_jobject(0) , m_jclass(0) , m_own_jclass(false) @@ -147,7 +156,7 @@ QJNIObject::QJNIObject(const char *className) } } -QJNIObject::QJNIObject(const char *className, const char *sig, ...) +QJNIObjectPrivate::QJNIObjectPrivate(const char *className, const char *sig, va_list args) : m_jobject(0) , m_jclass(0) , m_own_jclass(false) @@ -157,10 +166,7 @@ QJNIObject::QJNIObject(const char *className, const char *sig, ...) if (m_jclass) { jmethodID constructorId = getCachedMethodID(env, m_jclass, "<init>", sig); if (constructorId) { - va_list args; - va_start(args, sig); jobject obj = env->NewObjectV(m_jclass, constructorId, args); - va_end(args); if (obj) { m_jobject = env->NewGlobalRef(obj); env->DeleteLocalRef(obj); @@ -169,7 +175,7 @@ QJNIObject::QJNIObject(const char *className, const char *sig, ...) } } -QJNIObject::QJNIObject(jclass clazz) +QJNIObjectPrivate::QJNIObjectPrivate(jclass clazz) : m_jobject(0) , m_jclass(0) , m_own_jclass(true) @@ -189,7 +195,7 @@ QJNIObject::QJNIObject(jclass clazz) } } -QJNIObject::QJNIObject(jclass clazz, const char *sig, ...) +QJNIObjectPrivate::QJNIObjectPrivate(jclass clazz, const char *sig, va_list args) : m_jobject(0) , m_jclass(0) , m_own_jclass(true) @@ -200,10 +206,7 @@ QJNIObject::QJNIObject(jclass clazz, const char *sig, ...) if (m_jclass) { jmethodID constructorId = getCachedMethodID(env, m_jclass, "<init>", sig); if (constructorId) { - va_list args; - va_start(args, sig); jobject obj = env->NewObjectV(m_jclass, constructorId, args); - va_end(args); if (obj) { m_jobject = env->NewGlobalRef(obj); env->DeleteLocalRef(obj); @@ -213,7 +216,7 @@ QJNIObject::QJNIObject(jclass clazz, const char *sig, ...) } } -QJNIObject::QJNIObject(jobject obj) +QJNIObjectPrivate::QJNIObjectPrivate(jobject obj) : m_jobject(0) , m_jclass(0) , m_own_jclass(true) @@ -223,7 +226,7 @@ QJNIObject::QJNIObject(jobject obj) m_jclass = static_cast<jclass>(env->NewGlobalRef(env->GetObjectClass(m_jobject))); } -QJNIObject::~QJNIObject() +QJNIObjectPrivate::~QJNIObjectPrivate() { QAttachedJNIEnv env; if (m_jobject) @@ -232,6 +235,23 @@ QJNIObject::~QJNIObject() env->DeleteGlobalRef(m_jclass); } +QJNIObject::QJNIObject(const char *className, const char *sig, ...) +{ + va_list args; + va_start(args, sig); + d = QSharedPointer<QJNIObjectPrivate>(new QJNIObjectPrivate(className, sig, args)); + va_end(args); +} + +QJNIObject::QJNIObject(jclass clazz, const char *sig, ...) +{ + va_list args; + va_start(args, sig); + d = QSharedPointer<QJNIObjectPrivate>(new QJNIObjectPrivate(clazz, sig, args)); + va_end(args); +} + + bool QJNIObject::isClassAvailable(const char *className) { QAttachedJNIEnv env; @@ -248,11 +268,11 @@ template <> void QJNIObject::callMethod<void>(const char *methodName, const char *sig, ...) { QAttachedJNIEnv env; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - env->CallVoidMethodV(m_jobject, id, args); + env->CallVoidMethodV(d->m_jobject, id, args); va_end(args); } } @@ -262,11 +282,11 @@ jboolean QJNIObject::callMethod<jboolean>(const char *methodName, const char *si { QAttachedJNIEnv env; jboolean res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = env->CallBooleanMethodV(m_jobject, id, args); + res = env->CallBooleanMethodV(d->m_jobject, id, args); va_end(args); } return res; @@ -277,11 +297,11 @@ jbyte QJNIObject::callMethod<jbyte>(const char *methodName, const char *sig, ... { QAttachedJNIEnv env; jbyte res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = env->CallByteMethodV(m_jobject, id, args); + res = env->CallByteMethodV(d->m_jobject, id, args); va_end(args); } return res; @@ -292,11 +312,11 @@ jchar QJNIObject::callMethod<jchar>(const char *methodName, const char *sig, ... { QAttachedJNIEnv env; jchar res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = env->CallCharMethodV(m_jobject, id, args); + res = env->CallCharMethodV(d->m_jobject, id, args); va_end(args); } return res; @@ -307,11 +327,11 @@ jshort QJNIObject::callMethod<jshort>(const char *methodName, const char *sig, . { QAttachedJNIEnv env; jshort res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = env->CallShortMethodV(m_jobject, id, args); + res = env->CallShortMethodV(d->m_jobject, id, args); va_end(args); } return res; @@ -322,11 +342,11 @@ jint QJNIObject::callMethod<jint>(const char *methodName, const char *sig, ...) { QAttachedJNIEnv env; jint res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = env->CallIntMethodV(m_jobject, id, args); + res = env->CallIntMethodV(d->m_jobject, id, args); va_end(args); } return res; @@ -337,11 +357,11 @@ jlong QJNIObject::callMethod<jlong>(const char *methodName, const char *sig, ... { QAttachedJNIEnv env; jlong res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = env->CallLongMethodV(m_jobject, id, args); + res = env->CallLongMethodV(d->m_jobject, id, args); va_end(args); } return res; @@ -352,11 +372,11 @@ jfloat QJNIObject::callMethod<jfloat>(const char *methodName, const char *sig, . { QAttachedJNIEnv env; jfloat res = 0.f; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = env->CallFloatMethodV(m_jobject, id, args); + res = env->CallFloatMethodV(d->m_jobject, id, args); va_end(args); } return res; @@ -367,11 +387,11 @@ jdouble QJNIObject::callMethod<jdouble>(const char *methodName, const char *sig, { QAttachedJNIEnv env; jdouble res = 0.; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = env->CallDoubleMethodV(m_jobject, id, args); + res = env->CallDoubleMethodV(d->m_jobject, id, args); va_end(args); } return res; @@ -384,11 +404,11 @@ QJNILocalRef<jobject> QJNIObject::callObjectMethod<jobject>(const char *methodNa { QAttachedJNIEnv env; jobject res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = env->CallObjectMethodV(m_jobject, id, args); + res = env->CallObjectMethodV(d->m_jobject, id, args); va_end(args); } return QJNILocalRef<jobject>(res); @@ -401,11 +421,11 @@ QJNILocalRef<jstring> QJNIObject::callObjectMethod<jstring>(const char *methodNa { QAttachedJNIEnv env; jstring res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = static_cast<jstring>(env->CallObjectMethodV(m_jobject, id, args)); + res = static_cast<jstring>(env->CallObjectMethodV(d->m_jobject, id, args)); va_end(args); } return QJNILocalRef<jstring>(res); @@ -418,11 +438,11 @@ QJNILocalRef<jobjectArray> QJNIObject::callObjectMethod<jobjectArray>(const char { QAttachedJNIEnv env; jobjectArray res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = static_cast<jobjectArray>(env->CallObjectMethodV(m_jobject, id, args)); + res = static_cast<jobjectArray>(env->CallObjectMethodV(d->m_jobject, id, args)); va_end(args); } return QJNILocalRef<jobjectArray>(res); @@ -435,11 +455,11 @@ QJNILocalRef<jbooleanArray> QJNIObject::callObjectMethod<jbooleanArray>(const ch { QAttachedJNIEnv env; jbooleanArray res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = static_cast<jbooleanArray>(env->CallObjectMethodV(m_jobject, id, args)); + res = static_cast<jbooleanArray>(env->CallObjectMethodV(d->m_jobject, id, args)); va_end(args); } return QJNILocalRef<jbooleanArray>(res); @@ -452,11 +472,11 @@ QJNILocalRef<jbyteArray> QJNIObject::callObjectMethod<jbyteArray>(const char *me { QAttachedJNIEnv env; jbyteArray res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = static_cast<jbyteArray>(env->CallObjectMethodV(m_jobject, id, args)); + res = static_cast<jbyteArray>(env->CallObjectMethodV(d->m_jobject, id, args)); va_end(args); } return QJNILocalRef<jbyteArray>(res); @@ -469,11 +489,11 @@ QJNILocalRef<jcharArray> QJNIObject::callObjectMethod<jcharArray>(const char *me { QAttachedJNIEnv env; jcharArray res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = static_cast<jcharArray>(env->CallObjectMethodV(m_jobject, id, args)); + res = static_cast<jcharArray>(env->CallObjectMethodV(d->m_jobject, id, args)); va_end(args); } return QJNILocalRef<jcharArray>(res); @@ -486,11 +506,11 @@ QJNILocalRef<jshortArray> QJNIObject::callObjectMethod<jshortArray>(const char * { QAttachedJNIEnv env; jshortArray res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = static_cast<jshortArray>(env->CallObjectMethodV(m_jobject, id, args)); + res = static_cast<jshortArray>(env->CallObjectMethodV(d->m_jobject, id, args)); va_end(args); } return QJNILocalRef<jshortArray>(res); @@ -503,11 +523,11 @@ QJNILocalRef<jintArray> QJNIObject::callObjectMethod<jintArray>(const char *meth { QAttachedJNIEnv env; jintArray res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = static_cast<jintArray>(env->CallObjectMethodV(m_jobject, id, args)); + res = static_cast<jintArray>(env->CallObjectMethodV(d->m_jobject, id, args)); va_end(args); } return QJNILocalRef<jintArray>(res); @@ -520,11 +540,11 @@ QJNILocalRef<jlongArray> QJNIObject::callObjectMethod<jlongArray>(const char *me { QAttachedJNIEnv env; jlongArray res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = static_cast<jlongArray>(env->CallObjectMethodV(m_jobject, id, args)); + res = static_cast<jlongArray>(env->CallObjectMethodV(d->m_jobject, id, args)); va_end(args); } return QJNILocalRef<jlongArray>(res); @@ -537,11 +557,11 @@ QJNILocalRef<jfloatArray> QJNIObject::callObjectMethod<jfloatArray>(const char * { QAttachedJNIEnv env; jfloatArray res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = static_cast<jfloatArray>(env->CallObjectMethodV(m_jobject, id, args)); + res = static_cast<jfloatArray>(env->CallObjectMethodV(d->m_jobject, id, args)); va_end(args); } return QJNILocalRef<jfloatArray>(res); @@ -554,11 +574,11 @@ QJNILocalRef<jdoubleArray> QJNIObject::callObjectMethod<jdoubleArray>(const char { QAttachedJNIEnv env; jdoubleArray res = 0; - jmethodID id = getCachedMethodID(env, m_jclass, methodName, sig); + jmethodID id = getCachedMethodID(env, d->m_jclass, methodName, sig); if (id) { va_list args; va_start(args, sig); - res = static_cast<jdoubleArray>(env->CallObjectMethodV(m_jobject, id, args)); + res = static_cast<jdoubleArray>(env->CallObjectMethodV(d->m_jobject, id, args)); va_end(args); } return QJNILocalRef<jdoubleArray>(res); @@ -1796,9 +1816,9 @@ jboolean QJNIObject::getField<jboolean>(const char *fieldName) { QAttachedJNIEnv env; jboolean res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "Z"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "Z"); if (id) - res = env->GetBooleanField(m_jobject, id); + res = env->GetBooleanField(d->m_jobject, id); return res; } @@ -1808,9 +1828,9 @@ jbyte QJNIObject::getField<jbyte>(const char *fieldName) { QAttachedJNIEnv env; jbyte res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "B"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "B"); if (id) - res = env->GetByteField(m_jobject, id); + res = env->GetByteField(d->m_jobject, id); return res; } @@ -1820,9 +1840,9 @@ jchar QJNIObject::getField<jchar>(const char *fieldName) { QAttachedJNIEnv env; jchar res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "C"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "C"); if (id) - res = env->GetCharField(m_jobject, id); + res = env->GetCharField(d->m_jobject, id); return res; } @@ -1832,9 +1852,9 @@ jshort QJNIObject::getField<jshort>(const char *fieldName) { QAttachedJNIEnv env; jshort res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "S"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "S"); if (id) - res = env->GetShortField(m_jobject, id); + res = env->GetShortField(d->m_jobject, id); return res; } @@ -1844,9 +1864,9 @@ jint QJNIObject::getField<jint>(const char *fieldName) { QAttachedJNIEnv env; jint res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "I"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "I"); if (id) - res = env->GetIntField(m_jobject, id); + res = env->GetIntField(d->m_jobject, id); return res; } @@ -1856,9 +1876,9 @@ jlong QJNIObject::getField<jlong>(const char *fieldName) { QAttachedJNIEnv env; jlong res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "J"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "J"); if (id) - res = env->GetLongField(m_jobject, id); + res = env->GetLongField(d->m_jobject, id); return res; } @@ -1868,9 +1888,9 @@ jfloat QJNIObject::getField<jfloat>(const char *fieldName) { QAttachedJNIEnv env; jfloat res = 0.f; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "F"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "F"); if (id) - res = env->GetFloatField(m_jobject, id); + res = env->GetFloatField(d->m_jobject, id); return res; } @@ -1880,9 +1900,9 @@ jdouble QJNIObject::getField<jdouble>(const char *fieldName) { QAttachedJNIEnv env; jdouble res = 0.; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "D"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "D"); if (id) - res = env->GetDoubleField(m_jobject, id); + res = env->GetDoubleField(d->m_jobject, id); return res; } @@ -1892,9 +1912,9 @@ QJNILocalRef<jobject> QJNIObject::getObjectField<jobject>(const char *fieldName, { QAttachedJNIEnv env; jobject res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, sig); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, sig); if (id) - res = env->GetObjectField(m_jobject, id); + res = env->GetObjectField(d->m_jobject, id); return QJNILocalRef<jobject>(res); } @@ -1904,9 +1924,9 @@ QJNILocalRef<jbooleanArray> QJNIObject::getObjectField<jbooleanArray>(const char { QAttachedJNIEnv env; jbooleanArray res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[Z"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[Z"); if (id) - res = static_cast<jbooleanArray>(env->GetObjectField(m_jobject, id)); + res = static_cast<jbooleanArray>(env->GetObjectField(d->m_jobject, id)); return QJNILocalRef<jbooleanArray>(res); } @@ -1916,9 +1936,9 @@ QJNILocalRef<jbyteArray> QJNIObject::getObjectField<jbyteArray>(const char *fiel { QAttachedJNIEnv env; jbyteArray res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[B"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[B"); if (id) - res = static_cast<jbyteArray>(env->GetObjectField(m_jobject, id)); + res = static_cast<jbyteArray>(env->GetObjectField(d->m_jobject, id)); return QJNILocalRef<jbyteArray>(res); } @@ -1928,9 +1948,9 @@ QJNILocalRef<jcharArray> QJNIObject::getObjectField<jcharArray>(const char *fiel { QAttachedJNIEnv env; jcharArray res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[C"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[C"); if (id) - res = static_cast<jcharArray>(env->GetObjectField(m_jobject, id)); + res = static_cast<jcharArray>(env->GetObjectField(d->m_jobject, id)); return QJNILocalRef<jcharArray>(res); } @@ -1940,9 +1960,9 @@ QJNILocalRef<jshortArray> QJNIObject::getObjectField<jshortArray>(const char *fi { QAttachedJNIEnv env; jshortArray res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[S"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[S"); if (id) - res = static_cast<jshortArray>(env->GetObjectField(m_jobject, id)); + res = static_cast<jshortArray>(env->GetObjectField(d->m_jobject, id)); return QJNILocalRef<jshortArray>(res); } @@ -1952,9 +1972,9 @@ QJNILocalRef<jintArray> QJNIObject::getObjectField<jintArray>(const char *fieldN { QAttachedJNIEnv env; jintArray res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[I"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[I"); if (id) - res = static_cast<jintArray>(env->GetObjectField(m_jobject, id)); + res = static_cast<jintArray>(env->GetObjectField(d->m_jobject, id)); return QJNILocalRef<jintArray>(res); } @@ -1964,9 +1984,9 @@ QJNILocalRef<jlongArray> QJNIObject::getObjectField<jlongArray>(const char *fiel { QAttachedJNIEnv env; jlongArray res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[J"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[J"); if (id) - res = static_cast<jlongArray>(env->GetObjectField(m_jobject, id)); + res = static_cast<jlongArray>(env->GetObjectField(d->m_jobject, id)); return QJNILocalRef<jlongArray>(res); } @@ -1976,9 +1996,9 @@ QJNILocalRef<jfloatArray> QJNIObject::getObjectField<jfloatArray>(const char *fi { QAttachedJNIEnv env; jfloatArray res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[F"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[F"); if (id) - res = static_cast<jfloatArray>(env->GetObjectField(m_jobject, id)); + res = static_cast<jfloatArray>(env->GetObjectField(d->m_jobject, id)); return QJNILocalRef<jfloatArray>(res); } @@ -1988,9 +2008,9 @@ QJNILocalRef<jdoubleArray> QJNIObject::getObjectField<jdoubleArray>(const char * { QAttachedJNIEnv env; jdoubleArray res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[D"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[D"); if (id) - res = static_cast<jdoubleArray>(env->GetObjectField(m_jobject, id)); + res = static_cast<jdoubleArray>(env->GetObjectField(d->m_jobject, id)); return QJNILocalRef<jdoubleArray>(res); } @@ -2000,9 +2020,9 @@ QJNILocalRef<jstring> QJNIObject::getObjectField<jstring>(const char *fieldName) { QAttachedJNIEnv env; jstring res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "Ljava/lang/String;"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "Ljava/lang/String;"); if (id) - res = static_cast<jstring>(env->GetObjectField(m_jobject, id)); + res = static_cast<jstring>(env->GetObjectField(d->m_jobject, id)); return QJNILocalRef<jstring>(res); } @@ -2013,9 +2033,9 @@ QJNILocalRef<jobjectArray> QJNIObject::getObjectField<jobjectArray>(const char * { QAttachedJNIEnv env; jobjectArray res = 0; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, sig); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, sig); if (id) - res = static_cast<jobjectArray>(env->GetObjectField(m_jobject, id)); + res = static_cast<jobjectArray>(env->GetObjectField(d->m_jobject, id)); return QJNILocalRef<jobjectArray>(res); } @@ -2024,9 +2044,9 @@ template <> void QJNIObject::setField<jboolean>(const char *fieldName, jboolean value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "Z"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "Z"); if (id) - env->SetBooleanField(m_jobject, id, value); + env->SetBooleanField(d->m_jobject, id, value); } @@ -2034,9 +2054,9 @@ template <> void QJNIObject::setField<jbyte>(const char *fieldName, jbyte value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "B"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "B"); if (id) - env->SetByteField(m_jobject, id, value); + env->SetByteField(d->m_jobject, id, value); } @@ -2044,9 +2064,9 @@ template <> void QJNIObject::setField<jchar>(const char *fieldName, jchar value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "C"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "C"); if (id) - env->SetCharField(m_jobject, id, value); + env->SetCharField(d->m_jobject, id, value); } @@ -2054,9 +2074,9 @@ template <> void QJNIObject::setField<jshort>(const char *fieldName, jshort value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "S"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "S"); if (id) - env->SetShortField(m_jobject, id, value); + env->SetShortField(d->m_jobject, id, value); } @@ -2064,9 +2084,9 @@ template <> void QJNIObject::setField<jint>(const char *fieldName, jint value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "I"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "I"); if (id) - env->SetIntField(m_jobject, id, value); + env->SetIntField(d->m_jobject, id, value); } @@ -2074,9 +2094,9 @@ template <> void QJNIObject::setField<jlong>(const char *fieldName, jlong value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "J"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "J"); if (id) - env->SetLongField(m_jobject, id, value); + env->SetLongField(d->m_jobject, id, value); } @@ -2084,9 +2104,9 @@ template <> void QJNIObject::setField<jfloat>(const char *fieldName, jfloat value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "F"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "F"); if (id) - env->SetFloatField(m_jobject, id, value); + env->SetFloatField(d->m_jobject, id, value); } @@ -2094,9 +2114,9 @@ template <> void QJNIObject::setField<jdouble>(const char *fieldName, jdouble value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "D"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "D"); if (id) - env->SetDoubleField(m_jobject, id, value); + env->SetDoubleField(d->m_jobject, id, value); } @@ -2104,9 +2124,9 @@ template <> void QJNIObject::setField<jbooleanArray>(const char *fieldName, jbooleanArray value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[Z"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[Z"); if (id) - env->SetObjectField(m_jobject, id, value); + env->SetObjectField(d->m_jobject, id, value); } @@ -2114,9 +2134,9 @@ template <> void QJNIObject::setField<jbyteArray>(const char *fieldName, jbyteArray value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[B"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[B"); if (id) - env->SetObjectField(m_jobject, id, value); + env->SetObjectField(d->m_jobject, id, value); } @@ -2124,9 +2144,9 @@ template <> void QJNIObject::setField<jcharArray>(const char *fieldName, jcharArray value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[C"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[C"); if (id) - env->SetObjectField(m_jobject, id, value); + env->SetObjectField(d->m_jobject, id, value); } @@ -2134,9 +2154,9 @@ template <> void QJNIObject::setField<jshortArray>(const char *fieldName, jshortArray value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[S"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[S"); if (id) - env->SetObjectField(m_jobject, id, value); + env->SetObjectField(d->m_jobject, id, value); } @@ -2144,9 +2164,9 @@ template <> void QJNIObject::setField<jintArray>(const char *fieldName, jintArray value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[I"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[I"); if (id) - env->SetObjectField(m_jobject, id, value); + env->SetObjectField(d->m_jobject, id, value); } @@ -2154,9 +2174,9 @@ template <> void QJNIObject::setField<jlongArray>(const char *fieldName, jlongArray value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[J"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[J"); if (id) - env->SetObjectField(m_jobject, id, value); + env->SetObjectField(d->m_jobject, id, value); } @@ -2164,9 +2184,9 @@ template <> void QJNIObject::setField<jfloatArray>(const char *fieldName, jfloatArray value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[F"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[F"); if (id) - env->SetObjectField(m_jobject, id, value); + env->SetObjectField(d->m_jobject, id, value); } @@ -2174,9 +2194,9 @@ template <> void QJNIObject::setField<jdoubleArray>(const char *fieldName, jdoubleArray value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "[D"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "[D"); if (id) - env->SetObjectField(m_jobject, id, value); + env->SetObjectField(d->m_jobject, id, value); } @@ -2184,9 +2204,9 @@ template <> void QJNIObject::setField<jstring>(const char *fieldName, jstring value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, "Ljava/lang/String;"); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, "Ljava/lang/String;"); if (id) - env->SetObjectField(m_jobject, id, value); + env->SetObjectField(d->m_jobject, id, value); } @@ -2194,9 +2214,9 @@ template <> void QJNIObject::setField<jobject>(const char *fieldName, const char *sig, jobject value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, sig); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, sig); if (id) - env->SetObjectField(m_jobject, id, value); + env->SetObjectField(d->m_jobject, id, value); } @@ -2206,9 +2226,9 @@ void QJNIObject::setField<jobjectArray>(const char *fieldName, jobjectArray value) { QAttachedJNIEnv env; - jfieldID id = getCachedFieldID(env, m_jclass, fieldName, sig); + jfieldID id = getCachedFieldID(env, d->m_jclass, fieldName, sig); if (id) - env->SetObjectField(m_jobject, id, value); + env->SetObjectField(d->m_jobject, id, value); } diff --git a/src/platformsupport/jniconvenience/qjniobject_p.h b/src/platformsupport/jniconvenience/qjniobject_p.h index 6874765f06..8721ec3a6a 100644 --- a/src/platformsupport/jniconvenience/qjniobject_p.h +++ b/src/platformsupport/jniconvenience/qjniobject_p.h @@ -43,6 +43,7 @@ #define QJNIOBJECT_H #include <qglobal.h> +#include <qsharedpointer.h> #include <jni.h> QT_BEGIN_NAMESPACE @@ -72,20 +73,40 @@ class QJNILocalRef; * someObject.setField<jint>("fieldName", 10); * someObject.callMethod<void>("doStuff"); */ + +class QJNIObjectPrivate +{ +public: + QJNIObjectPrivate(const char *className); + QJNIObjectPrivate(const char *className, const char *sig, va_list args); + QJNIObjectPrivate(jclass clazz); + QJNIObjectPrivate(jclass clazz, const char *sig, va_list args); + QJNIObjectPrivate(jobject obj); + ~QJNIObjectPrivate(); + +private: + Q_DISABLE_COPY(QJNIObjectPrivate) + friend class QJNIObject; + jobject m_jobject; + jclass m_jclass; + bool m_own_jclass; +}; + class QJNIObject { public: - QJNIObject(const char *className); + explicit QJNIObject(const char *className) : d(new QJNIObjectPrivate(className)) { } QJNIObject(const char *className, const char *sig, ...); - QJNIObject(jclass clazz); + explicit QJNIObject(jclass clazz) : d(new QJNIObjectPrivate(clazz)) { } QJNIObject(jclass clazz, const char *sig, ...); - QJNIObject(jobject obj); - virtual ~QJNIObject(); + explicit QJNIObject(jobject obj) : d(new QJNIObjectPrivate(obj)) { } + + virtual ~QJNIObject() { } static bool isClassAvailable(const char *className); - bool isValid() const { return m_jobject != 0; } - jobject object() const { return m_jobject; } + bool isValid() const { return d->m_jobject != 0; } + jobject object() const { return d->m_jobject; } template <typename T> T callMethod(const char *methodName); @@ -158,10 +179,8 @@ public: template <typename T> static void setStaticField(jclass clazz, const char *fieldName, T value); -protected: - jobject m_jobject; - jclass m_jclass; - bool m_own_jclass; +private: + QSharedPointer<QJNIObjectPrivate> d; }; QT_END_NAMESPACE diff --git a/src/plugins/platforms/android/src/opengl/qandroidopenglplatformwindow.cpp b/src/plugins/platforms/android/src/opengl/qandroidopenglplatformwindow.cpp index 5362906e0e..24a7debd1f 100644 --- a/src/plugins/platforms/android/src/opengl/qandroidopenglplatformwindow.cpp +++ b/src/plugins/platforms/android/src/opengl/qandroidopenglplatformwindow.cpp @@ -69,7 +69,6 @@ void QAndroidOpenGLPlatformWindow::invalidateSurface() { QWindowSystemInterface::handleExposeEvent(window(), QRegion()); // Obscure event QWindowSystemInterface::flushWindowSystemEvents(); - QEglFSWindow::invalidateSurface(); m_window = 0; m_surface = 0; diff --git a/src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm b/src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm index 2ac9a5dac9..9a661ffe5a 100644 --- a/src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm +++ b/src/plugins/platforms/cocoa/qcocoaeventdispatcher.mm @@ -594,6 +594,7 @@ void QCocoaEventDispatcherPrivate::temporarilyStopAllModalSessions() if (info.session) { [NSApp endModalSession:info.session]; info.session = 0; + [(NSWindow*) info.nswindow release]; } } currentModalSessionCached = 0; diff --git a/src/plugins/platforms/cocoa/qcocoawindow.mm b/src/plugins/platforms/cocoa/qcocoawindow.mm index 20f767e240..46d3b7329e 100644 --- a/src/plugins/platforms/cocoa/qcocoawindow.mm +++ b/src/plugins/platforms/cocoa/qcocoawindow.mm @@ -1010,7 +1010,12 @@ qreal QCocoaWindow::devicePixelRatio() const { #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_7) { - return qreal([[m_contentView window] backingScaleFactor]); + NSWindow* window = [m_contentView window]; + if (window) { + return qreal([window backingScaleFactor]); + } else { + return 1.0; + } } else #endif { diff --git a/src/plugins/platforms/cocoa/qnsview.mm b/src/plugins/platforms/cocoa/qnsview.mm index e529e445ad..51c3953af1 100644 --- a/src/plugins/platforms/cocoa/qnsview.mm +++ b/src/plugins/platforms/cocoa/qnsview.mm @@ -285,6 +285,10 @@ static QTouchDevice *touchDevice = 0; Qt::WindowState newState = notificationName == NSWindowDidMiniaturizeNotification ? Qt::WindowMinimized : Qt::WindowNoState; [self notifyWindowStateChanged:newState]; + // NSWindowDidOrderOnScreenAndFinishAnimatingNotification is private API, and not + // emitted in 10.6, so we bring back the old behavior for that case alone. + if (newState == Qt::WindowNoState && QSysInfo::QSysInfo::MacintoshVersion == QSysInfo::MV_10_6) + m_platformWindow->exposeWindow(); } else if ([notificationName isEqualToString: @"NSWindowDidOrderOffScreenNotification"]) { m_platformWindow->obscureWindow(); } else if ([notificationName isEqualToString: @"NSWindowDidOrderOnScreenAndFinishAnimatingNotification"]) { diff --git a/src/plugins/platforms/qnx/qqnxbpseventfilter.cpp b/src/plugins/platforms/qnx/qqnxbpseventfilter.cpp index 133bf02fee..4c36a97ab6 100644 --- a/src/plugins/platforms/qnx/qqnxbpseventfilter.cpp +++ b/src/plugins/platforms/qnx/qqnxbpseventfilter.cpp @@ -226,9 +226,14 @@ bool QQnxBpsEventFilter::handleNavigatorEvent(bps_event_t *event) break; case NAVIGATOR_WINDOW_THUMBNAIL: m_navigatorEventHandler->handleWindowGroupStateChanged(id, Qt::WindowMinimized); +#if defined(Q_OS_BLACKBERRY_TABLET) + m_navigatorEventHandler->handleWindowGroupActivated(id); +#endif break; case NAVIGATOR_WINDOW_INVISIBLE: +#if defined(Q_OS_BLACKBERRY_TABLET) m_navigatorEventHandler->handleWindowGroupDeactivated(id); +#endif break; } diff --git a/src/plugins/platforms/qnx/qqnxrootwindow.cpp b/src/plugins/platforms/qnx/qqnxrootwindow.cpp index ff5866d1b7..b3f5c87176 100644 --- a/src/plugins/platforms/qnx/qqnxrootwindow.cpp +++ b/src/plugins/platforms/qnx/qqnxrootwindow.cpp @@ -188,35 +188,8 @@ void QQnxRootWindow::makeTranslucent() int result; errno = 0; - result = screen_destroy_window_buffers(m_window); - if (result != 0) { - qFatal("QQnxRootWindow: failed to destroy window buffer, errno=%d", errno); - } - - QRect geometry = m_screen->geometry(); - errno = 0; - int val[2]; - val[0] = geometry.width(); - val[1] = geometry.height(); - result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_BUFFER_SIZE, val); - if (result != 0) { - qFatal("QQnxRootWindow: failed to set window buffer size, errno=%d", errno); - } - - errno = 0; - result = screen_create_window_buffers(m_window, 1); - if (result != 0) { - qFatal("QQNX: failed to create window buffer, errno=%d", errno); - } - - // Install an alpha channel on the root window. - // - // This is necessary in order to avoid interfering with any particular - // toplevel widget's QQnxWindow window instance from showing transparent - // if it desires. - errno = 0; - val[0] = SCREEN_TRANSPARENCY_SOURCE_OVER; - result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_TRANSPARENCY, val); + const int val = SCREEN_TRANSPARENCY_DISCARD; + result = screen_set_window_property_iv(m_window, SCREEN_PROPERTY_TRANSPARENCY, &val); if (result != 0) { qFatal("QQnxRootWindow: failed to set window transparency, errno=%d", errno); } diff --git a/src/plugins/platforms/qnx/qqnxwindow.cpp b/src/plugins/platforms/qnx/qqnxwindow.cpp index 45e565f24f..9b9576c88b 100644 --- a/src/plugins/platforms/qnx/qqnxwindow.cpp +++ b/src/plugins/platforms/qnx/qqnxwindow.cpp @@ -432,15 +432,27 @@ QQnxBuffer &QQnxWindow::renderBuffer() // Get all buffers available for rendering errno = 0; screen_buffer_t buffers[MAX_BUFFER_COUNT]; - const int result = screen_get_window_property_pv(m_window, SCREEN_PROPERTY_RENDER_BUFFERS, (void **)buffers); + int result = screen_get_window_property_pv(m_window, SCREEN_PROPERTY_RENDER_BUFFERS, (void **)buffers); if (result != 0) qFatal("QQnxWindow: failed to query window buffers, errno=%d", errno); - // Wrap each buffer + // Wrap each buffer and clear for (int i = 0; i < MAX_BUFFER_COUNT; ++i) { m_buffers[i] = QQnxBuffer(buffers[i]); + + // Clear Buffer + errno = 0; + int bg[] = { SCREEN_BLIT_COLOR, 0x00000000, SCREEN_BLIT_END }; + result = screen_fill(m_screen->nativeContext(), buffers[i], bg); + if (result != 0) + qFatal("QQnxWindow: failed to clear window buffer, errno=%d", errno); } + errno = 0; + result = screen_flush_blits(m_screen->nativeContext(), 0); + if (result != 0) + qFatal("QQnxWindow: failed to flush blits, errno=%d", errno); + // Use the first available render buffer m_currentBufferIndex = 0; m_previousBufferIndex = -1; diff --git a/src/plugins/platforms/windows/qwindowsintegration.cpp b/src/plugins/platforms/windows/qwindowsintegration.cpp index fc2ba454df..754d7a0288 100644 --- a/src/plugins/platforms/windows/qwindowsintegration.cpp +++ b/src/plugins/platforms/windows/qwindowsintegration.cpp @@ -395,6 +395,8 @@ bool QWindowsIntegration::hasCapability(QPlatformIntegration::Capability cap) co return true; case MultipleWindows: return true; + case ForeignWindows: + return true; default: return QPlatformIntegration::hasCapability(cap); } diff --git a/src/plugins/platforms/windows/qwindowsscreen.cpp b/src/plugins/platforms/windows/qwindowsscreen.cpp index f616972aa0..530ebc38b7 100644 --- a/src/plugins/platforms/windows/qwindowsscreen.cpp +++ b/src/plugins/platforms/windows/qwindowsscreen.cpp @@ -98,35 +98,39 @@ BOOL QT_WIN_CALLBACK monitorEnumCallback(HMONITOR hMonitor, HDC, LPRECT, LPARAM WindowsScreenDataList *result = reinterpret_cast<WindowsScreenDataList *>(p); QWindowsScreenData data; data.geometry = QRect(QPoint(info.rcMonitor.left, info.rcMonitor.top), QPoint(info.rcMonitor.right - 1, info.rcMonitor.bottom - 1)); + data.name = QString::fromWCharArray(info.szDevice); + if (data.name == QLatin1String("WinDisc")) { + data.flags |= QWindowsScreenData::LockScreen; + } else { #ifdef Q_OS_WINCE - //Windows CE, just supports one Display and expects to get only DISPLAY, - //instead of DISPLAY0 and so on, which are passed by info.szDevice - HDC hdc = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL); + //Windows CE, just supports one Display and expects to get only DISPLAY, + //instead of DISPLAY0 and so on, which are passed by info.szDevice + HDC hdc = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL); #else - HDC hdc = CreateDC(info.szDevice, NULL, NULL, NULL); + HDC hdc = CreateDC(info.szDevice, NULL, NULL, NULL); #endif - if (hdc) { - data.dpi = deviceDPI(hdc); - data.depth = GetDeviceCaps(hdc, BITSPIXEL); - data.format = data.depth == 16 ? QImage::Format_RGB16 : QImage::Format_RGB32; - data.physicalSizeMM = QSizeF(GetDeviceCaps(hdc, HORZSIZE), GetDeviceCaps(hdc, VERTSIZE)); - const int refreshRate = GetDeviceCaps(hdc, VREFRESH); - if (refreshRate > 1) // 0,1 means heardware default. - data.refreshRateHz = refreshRate; - DeleteDC(hdc); - } else { - qWarning("%s: Unable to obtain handle for monitor '%s', defaulting to %g DPI.", - __FUNCTION__, qPrintable(QString::fromWCharArray(info.szDevice)), - data.dpi.first); - } + if (hdc) { + data.dpi = deviceDPI(hdc); + data.depth = GetDeviceCaps(hdc, BITSPIXEL); + data.format = data.depth == 16 ? QImage::Format_RGB16 : QImage::Format_RGB32; + data.physicalSizeMM = QSizeF(GetDeviceCaps(hdc, HORZSIZE), GetDeviceCaps(hdc, VERTSIZE)); + const int refreshRate = GetDeviceCaps(hdc, VREFRESH); + if (refreshRate > 1) // 0,1 means hardware default. + data.refreshRateHz = refreshRate; + DeleteDC(hdc); + } else { + qWarning("%s: Unable to obtain handle for monitor '%s', defaulting to %g DPI.", + __FUNCTION__, qPrintable(QString::fromWCharArray(info.szDevice)), + data.dpi.first); + } // CreateDC() failed + } // not lock screen data.geometry = QRect(QPoint(info.rcMonitor.left, info.rcMonitor.top), QPoint(info.rcMonitor.right - 1, info.rcMonitor.bottom - 1)); data.availableGeometry = QRect(QPoint(info.rcWork.left, info.rcWork.top), QPoint(info.rcWork.right - 1, info.rcWork.bottom - 1)); data.orientation = data.geometry.height() > data.geometry.width() ? Qt::PortraitOrientation : Qt::LandscapeOrientation; // EnumDisplayMonitors (as opposed to EnumDisplayDevices) enumerates only // virtual desktop screens. - data.name = QString::fromWCharArray(info.szDevice); - data.flags = QWindowsScreenData::VirtualDesktop; + data.flags |= QWindowsScreenData::VirtualDesktop; if (info.dwFlags & MONITORINFOF_PRIMARY) { data.flags |= QWindowsScreenData::PrimaryScreen; // QPlatformIntegration::screenAdded() documentation specifies that first @@ -162,6 +166,8 @@ static QDebug operator<<(QDebug dbg, const QWindowsScreenData &d) nospace << " primary"; if (d.flags & QWindowsScreenData::VirtualDesktop) nospace << " virtual desktop"; + if (d.flags & QWindowsScreenData::LockScreen) + nospace << " lock screen"; return dbg; } @@ -392,7 +398,8 @@ static inline int indexOfMonitor(const QList<QWindowsScreenData> &screenData, bool QWindowsScreenManager::handleScreenChanges() { // Look for changed monitors, add new ones - const WindowsScreenDataList newDataList = monitorData(); + WindowsScreenDataList newDataList = monitorData(); + const bool lockScreen = newDataList.size() == 1 && (newDataList.front().flags & QWindowsScreenData::LockScreen); foreach (const QWindowsScreenData &newData, newDataList) { const int existingIndex = indexOfMonitor(m_screens, newData.name); if (existingIndex != -1) { @@ -405,14 +412,17 @@ bool QWindowsScreenManager::handleScreenChanges() qDebug() << "New Monitor: " << newData; } // exists } // for new screens. - // Remove deleted ones. - for (int i = m_screens.size() - 1; i >= 0; --i) { - if (indexOfMonitor(newDataList, m_screens.at(i)->data().name) == -1) { - if (QWindowsContext::verboseWindows) - qDebug() << "Removing Monitor: " << m_screens.at(i) ->data(); - delete m_screens.takeAt(i); - } // not found - } // for existing screens + // Remove deleted ones but keep main monitors if we get only the + // temporary lock screen to avoid window recreation (QTBUG-33062). + if (!lockScreen) { + for (int i = m_screens.size() - 1; i >= 0; --i) { + if (indexOfMonitor(newDataList, m_screens.at(i)->data().name) == -1) { + if (QWindowsContext::verboseWindows) + qDebug() << "Removing Monitor: " << m_screens.at(i) ->data(); + delete m_screens.takeAt(i); + } // not found + } // for existing screens + } // not lock screen return true; } diff --git a/src/plugins/platforms/windows/qwindowsscreen.h b/src/plugins/platforms/windows/qwindowsscreen.h index 216973125b..930814a17d 100644 --- a/src/plugins/platforms/windows/qwindowsscreen.h +++ b/src/plugins/platforms/windows/qwindowsscreen.h @@ -59,7 +59,8 @@ struct QWindowsScreenData enum Flags { PrimaryScreen = 0x1, - VirtualDesktop = 0x2 + VirtualDesktop = 0x2, + LockScreen = 0x4 // Temporary screen existing during user change, etc. }; QWindowsScreenData(); diff --git a/src/plugins/platforms/windows/qwindowswindow.cpp b/src/plugins/platforms/windows/qwindowswindow.cpp index 8ec10294a2..ace18ddf5b 100644 --- a/src/plugins/platforms/windows/qwindowswindow.cpp +++ b/src/plugins/platforms/windows/qwindowswindow.cpp @@ -485,6 +485,18 @@ QWindowsWindow::WindowData qDebug().nospace() << "Created desktop window " << w << result.hwnd; return result; } + if ((flags & Qt::WindowType_Mask) == Qt::ForeignWindow) { + result.hwnd = reinterpret_cast<HWND>(w->winId()); + Q_ASSERT(result.hwnd); + const LONG_PTR style = GetWindowLongPtr(result.hwnd, GWL_STYLE); + const LONG_PTR exStyle = GetWindowLongPtr(result.hwnd, GWL_EXSTYLE); + result.geometry = frameGeometry(result.hwnd, !GetParent(result.hwnd)); + result.frame = QWindowsGeometryHint::frame(style, exStyle); + result.embedded = false; + if (QWindowsContext::verboseWindows) + qDebug() << "Foreign window: " << w << result.hwnd << result.geometry << result.frame; + return result; + } const HINSTANCE appinst = (HINSTANCE)GetModuleHandle(0); @@ -894,7 +906,7 @@ void QWindowsWindow::destroyWindow() } } #endif // !Q_OS_WINCE - if (m_data.hwnd != GetDesktopWindow()) + if (m_data.hwnd != GetDesktopWindow() && window()->type() != Qt::ForeignWindow) DestroyWindow(m_data.hwnd); context->removeWindow(m_data.hwnd); m_data.hwnd = 0; @@ -1408,14 +1420,27 @@ void QWindowsWindow::handleWindowStateChange(Qt::WindowState state) handleHidden(); QWindowSystemInterface::flushWindowSystemEvents(); // Tell QQuickWindow to stop rendering now. break; - case Qt::WindowNoState: + case Qt::WindowNoState: { // QTBUG-17548: We send expose events when receiving WM_Paint, but for - // layered windows, we won't receive any WM_Paint. - if (GetWindowLongPtr(m_data.hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) { - fireExpose(QRegion(0, 0, window()->width(), window()->height())); - if (!QWindowsContext::instance()->asyncExpose()) - QWindowSystemInterface::flushWindowSystemEvents(); + // layered windows and transient children, we won't receive any WM_Paint. + QWindow *w = window(); + bool exposeEventsSent = false; + if (isLayered()) { + fireExpose(QRegion(0, 0, w->width(), w->height())); + exposeEventsSent = true; } + foreach (QWindow *child, QGuiApplication::allWindows()) { + if (child != w && child->isVisible() && child->transientParent() == w) { + QWindowsWindow *platformWindow = QWindowsWindow::baseWindowOf(child); + if (platformWindow->isLayered()) { + platformWindow->fireExpose(QRegion(0, 0, child->width(), child->height())); + exposeEventsSent = true; + } + } + } + if (exposeEventsSent && !QWindowsContext::instance()->asyncExpose()) + QWindowSystemInterface::flushWindowSystemEvents(); + } break; default: break; diff --git a/src/plugins/platforms/windows/qwindowswindow.h b/src/plugins/platforms/windows/qwindowswindow.h index f7d142fc36..afcfa8b821 100644 --- a/src/plugins/platforms/windows/qwindowswindow.h +++ b/src/plugins/platforms/windows/qwindowswindow.h @@ -229,6 +229,7 @@ public: static inline void setUserDataOf(HWND hwnd, void *ud); static bool setWindowLayered(HWND hwnd, Qt::WindowFlags flags, bool hasAlpha, qreal opacity); + bool isLayered() const; HDC getDC(); void releaseDC(); @@ -375,6 +376,15 @@ inline void QWindowsWindow::destroyIcon() } } +inline bool QWindowsWindow::isLayered() const +{ +#ifndef Q_OS_WINCE + return GetWindowLongPtr(m_data.hwnd, GWL_EXSTYLE) & WS_EX_LAYERED; +#else + return false; +#endif +} + QT_END_NAMESPACE Q_DECLARE_METATYPE(QMargins) diff --git a/src/plugins/platforms/xcb/qxcbbackingstore.cpp b/src/plugins/platforms/xcb/qxcbbackingstore.cpp index 1f2485db0d..dc677cd3be 100644 --- a/src/plugins/platforms/xcb/qxcbbackingstore.cpp +++ b/src/plugins/platforms/xcb/qxcbbackingstore.cpp @@ -306,6 +306,10 @@ void QXcbBackingStore::flush(QWindow *window, const QRegion ®ion, const QPoin Q_XCB_NOOP(connection()); QXcbWindow *platformWindow = static_cast<QXcbWindow *>(window->handle()); + if (!platformWindow) { + qWarning("QXcbBackingStore::flush: QWindow has no platform window (QTBUG-32681)"); + return; + } QVector<QRect> rects = clipped.rects(); for (int i = 0; i < rects.size(); ++i) diff --git a/src/plugins/platforms/xcb/qxcbconnection.cpp b/src/plugins/platforms/xcb/qxcbconnection.cpp index 3f717ae2df..e594f1fedc 100644 --- a/src/plugins/platforms/xcb/qxcbconnection.cpp +++ b/src/plugins/platforms/xcb/qxcbconnection.cpp @@ -998,8 +998,11 @@ void QXcbEventReader::run() emit eventPending(); } + m_mutex.lock(); for (int i = 0; i < m_events.size(); ++i) free(m_events.at(i)); + m_events.clear(); + m_mutex.unlock(); } void QXcbEventReader::addEvent(xcb_generic_event_t *event) diff --git a/src/sql/drivers/ibase/qsql_ibase.cpp b/src/sql/drivers/ibase/qsql_ibase.cpp index bd97db189c..e4979e54a4 100644 --- a/src/sql/drivers/ibase/qsql_ibase.cpp +++ b/src/sql/drivers/ibase/qsql_ibase.cpp @@ -240,7 +240,7 @@ static ISC_TIMESTAMP toTimeStamp(const QDateTime &dt) static QDateTime fromTimeStamp(char *buffer) { static const QDate bd(1858, 11, 17); - QTime t; + QTime t(0, 0); QDate d; // have to demangle the structure ourselves because isc_decode_time diff --git a/src/tools/moc/generator.cpp b/src/tools/moc/generator.cpp index 4757fdad93..50da6d2e54 100644 --- a/src/tools/moc/generator.cpp +++ b/src/tools/moc/generator.cpp @@ -184,6 +184,18 @@ bool Generator::registerableMetaType(const QByteArray &propertyType) return false; } +/* returns true if name and qualifiedName refers to the same name. + * If qualified name is "A::B::C", it returns true for "C", "B::C" or "A::B::C" */ +static bool qualifiedNameEquals(const QByteArray &qualifiedName, const QByteArray &name) +{ + if (qualifiedName == name) + return true; + int index = qualifiedName.indexOf("::"); + if (index == -1) + return false; + return qualifiedNameEquals(qualifiedName.mid(index+2), name); +} + void Generator::generateCode() { bool isQt = (cdef->classname == "Qt"); @@ -431,7 +443,7 @@ void Generator::generateCode() int s = p.type.lastIndexOf("::"); if (s > 0) { QByteArray scope = p.type.left(s); - if (scope != "Qt" && scope != cdef->classname && !extraList.contains(scope)) + if (scope != "Qt" && !qualifiedNameEquals(cdef->qualified, scope) && !extraList.contains(scope)) extraList += scope; } } @@ -446,7 +458,7 @@ void Generator::generateCode() int s = enumKey.lastIndexOf("::"); if (s > 0) { QByteArray scope = enumKey.left(s); - if (scope != "Qt" && scope != cdef->classname && !extraList.contains(scope)) + if (scope != "Qt" && !qualifiedNameEquals(cdef->qualified, scope) && !extraList.contains(scope)) extraList += scope; } } @@ -972,9 +984,9 @@ void Generator::generateMetacall() if (!p.notify.isEmpty() && p.notifyId != -1) { const FunctionDef &f = cdef->signalList.at(p.notifyId); if (f.arguments.size() == 0) - fprintf(out, " emit %s();\n", p.notify.constData()); + fprintf(out, " Q_EMIT %s();\n", p.notify.constData()); else if (f.arguments.size() == 1 && f.arguments.at(0).normalizedType == p.type) - fprintf(out, " emit %s(%s%s);\n", + fprintf(out, " Q_EMIT %s(%s%s);\n", p.notify.constData(), prefix.constData(), p.member.constData()); } fprintf(out, " }\n"); diff --git a/src/tools/moc/preprocessor.cpp b/src/tools/moc/preprocessor.cpp index 8f4b84a9c8..06758e67bd 100644 --- a/src/tools/moc/preprocessor.cpp +++ b/src/tools/moc/preprocessor.cpp @@ -645,7 +645,7 @@ Symbols Preprocessor::macroExpandIdentifier(Preprocessor *that, SymbolStack &sym // 0 argument macros are a bit special. They are ok if the // argument is pure whitespace or empty (macro.arguments.size() != 0 || arguments.size() != 1 || !arguments.at(0).isEmpty())) - that->error("Macro argument mismatch."); + that->warning("Macro argument mismatch."); // now replace the macro arguments with the expanded arguments enum Mode { @@ -662,7 +662,7 @@ Symbols Preprocessor::macroExpandIdentifier(Preprocessor *that, SymbolStack &sym } int index = macro.arguments.indexOf(s); if (mode == Normal) { - if (index >= 0) { + if (index >= 0 && index < arguments.size()) { // each argument undoergoes macro expansion if it's not used as part of a # or ## if (i == macro.symbols.size() - 1 || macro.symbols.at(i + 1).token != PP_HASHHASH) { Symbols arg = arguments.at(index); diff --git a/src/tools/qdoc/doc/qdoc-minimum-qdocconf.qdoc b/src/tools/qdoc/doc/qdoc-minimum-qdocconf.qdoc new file mode 100644 index 0000000000..4289f357e9 --- /dev/null +++ b/src/tools/qdoc/doc/qdoc-minimum-qdocconf.qdoc @@ -0,0 +1,86 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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$ +** +****************************************************************************/ +/*! +\page qdoc-minimum-qdocconf.html +\title A minimal qdocconf file with comments + +\brief Describes a minimal .qdocconf file + +Below you will find the full contents of qtgui.qdocconf. The subsequent section will discuss +every statement in the qdocconf file. + +\code + #include(compat.qdocconf) + outputdir = html + headerdirs = . + sourcedirs = . + exampledirs = . + imagedirs = ./images +\endcode + +\title Notes + +\code + #include(compat.qdocconf) +\endcode + +For compatibility with older versions of Qt, it is recommended +to include compat.qdocconf. + +\code + outputdir = html +\endcode + +QDoc will put the documentation generated in the html directory. + +\code + headerdirs = . +\endcode + +The header file associated with the \e .cpp source files can be found in the +current directory. + +\code + sourcedirs = . +\endcode + +The current directory is the directory containing the source files: the \e .cpp +and \e .qdoc files used in the documentation. + +\code + exampledirs = . +\endcode + +The source code of the example files can be found in the current directory. + +\code + imagedirs = ./images +\endcode + +The image files can be found in the underlying directory "images". + +*/ diff --git a/src/tools/qdoc/doc/qtgui-qdocconf.qdoc b/src/tools/qdoc/doc/qtgui-qdocconf.qdoc index 7e6da0feb5..767934986f 100644 --- a/src/tools/qdoc/doc/qtgui-qdocconf.qdoc +++ b/src/tools/qdoc/doc/qtgui-qdocconf.qdoc @@ -83,6 +83,8 @@ every statement in the qdocconf file. sourcedirs += .. \ ../../../examples/gui/doc/src + excludedirs = ../../../examples/gui/doc/src/tmp + exampledirs += ../../../examples/gui \ snippets @@ -273,14 +275,30 @@ Add the specified directories to the list of directories containing the \e .cpp \e .qdoc files used in the documentation. \code + excludedirs = ../../../examples/gui/doc/src/tmp +\endcode + +The \c excludedirs variable is for listing directories that should not be processed +by qdoc, even if the same directories are included by the \c sourcedirs or \c headerdirs +variables. + +When executed, QDoc will ignore the directories listed. +\sa excludefiles + +\code exampledirs += ../../../examples/gui \ snippets \endcode +\sa examples \sa examplesinstallpath Add the two directories specified to the list of directories containing the source code of the example files. +If QDoc encounters both \c exampledirs and \c examples, it will look first in the +\c examples directory. QDoc will accept the first matching file it finds. QDoc will +search in the directories specified, not in their subdirectories. + \code imagedirs += images \ ../../../examples/gui/doc/images \ diff --git a/src/widgets/kernel/qwidget_qpa.cpp b/src/widgets/kernel/qwidget_qpa.cpp index f0846bea6b..665aa4b17a 100644 --- a/src/widgets/kernel/qwidget_qpa.cpp +++ b/src/widgets/kernel/qwidget_qpa.cpp @@ -900,6 +900,8 @@ void QWidgetPrivate::createTLSysExtra() extra->topextra->window->setMinimumSize(QSize(extra->minw, extra->minh)); if (extra->maxw != QWIDGETSIZE_MAX || extra->maxh != QWIDGETSIZE_MAX) extra->topextra->window->setMaximumSize(QSize(extra->maxw, extra->maxh)); + if (extra->topextra->opacity != 255 && q->isWindow()) + extra->topextra->window->setOpacity(qreal(extra->topextra->opacity) / qreal(255)); #ifdef Q_OS_WIN // Pass on native parent handle for Widget embedded into Active X. const QVariant activeXNativeParentHandle = q->property(activeXNativeParentHandleProperty); diff --git a/src/widgets/styles/qcommonstyle.cpp b/src/widgets/styles/qcommonstyle.cpp index 0c1ae56349..539cc70eb7 100644 --- a/src/widgets/styles/qcommonstyle.cpp +++ b/src/widgets/styles/qcommonstyle.cpp @@ -1330,7 +1330,6 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt, break; #ifndef QT_NO_MENU case CE_MenuScroller: { - p->fillRect(opt->rect, opt->palette.background()); QStyleOption arrowOpt = *opt; arrowOpt.state |= State_Enabled; proxy()->drawPrimitive(((opt->state & State_DownArrow) ? PE_IndicatorArrowDown : PE_IndicatorArrowUp), diff --git a/src/widgets/styles/qwindowsvistastyle.cpp b/src/widgets/styles/qwindowsvistastyle.cpp index e442e53bde..22458eb96f 100644 --- a/src/widgets/styles/qwindowsvistastyle.cpp +++ b/src/widgets/styles/qwindowsvistastyle.cpp @@ -1830,29 +1830,31 @@ void QWindowsVistaStyle::drawComplexControl(ComplexControl control, const QStyle int gw = size.cx, gh = size.cy; - QRect gripperBounds; - if (flags & State_Horizontal && ((swidth - contentsMargin.cxLeftWidth - contentsMargin.cxRightWidth) > gw)) { - gripperBounds.setLeft(theme.rect.left() + swidth/2 - gw/2); - gripperBounds.setTop(theme.rect.top() + sheight/2 - gh/2); - gripperBounds.setWidth(gw); - gripperBounds.setHeight(gh); - } else if ((sheight - contentsMargin.cyTopHeight - contentsMargin.cyBottomHeight) > gh) { - gripperBounds.setLeft(theme.rect.left() + swidth/2 - gw/2); - gripperBounds.setTop(theme.rect.top() + sheight/2 - gh/2); - gripperBounds.setWidth(gw); - gripperBounds.setHeight(gh); - } + if (QSysInfo::WindowsVersion < QSysInfo::WV_WINDOWS8) { + QRect gripperBounds; + if (flags & State_Horizontal && ((swidth - contentsMargin.cxLeftWidth - contentsMargin.cxRightWidth) > gw)) { + gripperBounds.setLeft(theme.rect.left() + swidth/2 - gw/2); + gripperBounds.setTop(theme.rect.top() + sheight/2 - gh/2); + gripperBounds.setWidth(gw); + gripperBounds.setHeight(gh); + } else if ((sheight - contentsMargin.cyTopHeight - contentsMargin.cyBottomHeight) > gh) { + gripperBounds.setLeft(theme.rect.left() + swidth/2 - gw/2); + gripperBounds.setTop(theme.rect.top() + sheight/2 - gh/2); + gripperBounds.setWidth(gw); + gripperBounds.setHeight(gh); + } - // Draw gripper if there is enough space - if (!gripperBounds.isEmpty() && flags & State_Enabled) { - painter->save(); - XPThemeData grippBackground = theme; - grippBackground.partId = flags & State_Horizontal ? SBP_LOWERTRACKHORZ : SBP_LOWERTRACKVERT; - theme.rect = gripperBounds; - painter->setClipRegion(d->region(theme));// Only change inside the region of the gripper - d->drawBackground(grippBackground);// The gutter is the grippers background - d->drawBackground(theme); // Transparent gripper ontop of background - painter->restore(); + // Draw gripper if there is enough space + if (!gripperBounds.isEmpty() && flags & State_Enabled) { + painter->save(); + XPThemeData grippBackground = theme; + grippBackground.partId = flags & State_Horizontal ? SBP_LOWERTRACKHORZ : SBP_LOWERTRACKVERT; + theme.rect = gripperBounds; + painter->setClipRegion(d->region(theme));// Only change inside the region of the gripper + d->drawBackground(grippBackground);// The gutter is the grippers background + d->drawBackground(theme); // Transparent gripper ontop of background + painter->restore(); + } } } } diff --git a/tests/auto/cmake/CMakeLists.txt b/tests/auto/cmake/CMakeLists.txt index 0f794915ee..87d8a802f3 100644 --- a/tests/auto/cmake/CMakeLists.txt +++ b/tests/auto/cmake/CMakeLists.txt @@ -129,3 +129,8 @@ expect_pass(test_opengl_lib) if (NOT CMAKE_VERSION VERSION_LESS 2.8.11) expect_pass(test_interface) endif() + +if (NOT CMAKE_VERSION VERSION_LESS 2.8.12) + expect_pass(test_interface_link_libraries) + expect_pass(test_moc_macro_target) +endif() diff --git a/tests/auto/cmake/test_interface_link_libraries/CMakeLists.txt b/tests/auto/cmake/test_interface_link_libraries/CMakeLists.txt new file mode 100644 index 0000000000..d747a43c4a --- /dev/null +++ b/tests/auto/cmake/test_interface_link_libraries/CMakeLists.txt @@ -0,0 +1,21 @@ + +cmake_minimum_required(VERSION 2.8) + +project(test_interface_link_libraries) + +find_package(Qt5Gui REQUIRED) + +set(CMAKE_AUTOMOC ON) +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +cmake_policy(SET CMP0022 NEW) + +include(GenerateExportHeader) + +add_library(somelib SHARED somelib.cpp) +generate_export_header(somelib) +set_property(TARGET somelib PROPERTY LINK_LIBRARIES Qt5::Gui) +set_property(TARGET somelib PROPERTY INTERFACE_LINK_LIBRARIES Qt5::Gui) + +add_executable(mainexe main.cpp) +set_property(TARGET mainexe PROPERTY LINK_LIBRARIES somelib) diff --git a/tests/auto/cmake/test_interface_link_libraries/main.cpp b/tests/auto/cmake/test_interface_link_libraries/main.cpp new file mode 100644 index 0000000000..4ea2204d38 --- /dev/null +++ b/tests/auto/cmake/test_interface_link_libraries/main.cpp @@ -0,0 +1,48 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Stephen Kelly <stephen.kelly@kdab.com> +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "somelib.h" + +int main(int,char**) +{ + SomeObject so; + return so.value(); +} diff --git a/tests/auto/cmake/test_interface_link_libraries/somelib.cpp b/tests/auto/cmake/test_interface_link_libraries/somelib.cpp new file mode 100644 index 0000000000..633540b164 --- /dev/null +++ b/tests/auto/cmake/test_interface_link_libraries/somelib.cpp @@ -0,0 +1,52 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Stephen Kelly <stephen.kelly@kdab.com> +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "somelib.h" + +SomeObject::SomeObject(QObject *parent) + : QTextDocument(parent) +{ +} + +int SomeObject::value() +{ + return 0; +} diff --git a/tests/auto/cmake/test_interface_link_libraries/somelib.h b/tests/auto/cmake/test_interface_link_libraries/somelib.h new file mode 100644 index 0000000000..76b35b6b6a --- /dev/null +++ b/tests/auto/cmake/test_interface_link_libraries/somelib.h @@ -0,0 +1,58 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Stephen Kelly <stephen.kelly@kdab.com> +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SOMELIB_H +#define SOMELIB_H + +#include "somelib_export.h" + +#include <QTextDocument> + +class SOMELIB_EXPORT SomeObject : QTextDocument +{ + Q_OBJECT +public: + explicit SomeObject(QObject *parent = 0); + + int value(); +}; + +#endif diff --git a/tests/auto/cmake/test_moc_macro_target/CMakeLists.txt b/tests/auto/cmake/test_moc_macro_target/CMakeLists.txt new file mode 100644 index 0000000000..e97ac199e8 --- /dev/null +++ b/tests/auto/cmake/test_moc_macro_target/CMakeLists.txt @@ -0,0 +1,23 @@ + +cmake_minimum_required(VERSION 2.8) + +project(test_moc_macro_target) + +find_package(Qt5Core REQUIRED) + +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +qt5_generate_moc(main_gen_test.cpp + "${CMAKE_CURRENT_BINARY_DIR}/main_gen_test.moc" + TARGET Qt5GenerateMacroTest +) +add_executable(Qt5GenerateMacroTest WIN32 main_gen_test.cpp "${CMAKE_CURRENT_BINARY_DIR}/main_gen_test.moc") +target_include_directories(Qt5GenerateMacroTest PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/interface") +target_link_libraries(Qt5GenerateMacroTest Qt5::Core) + +qt5_wrap_cpp(moc_file mywrapobject.h + TARGET Qt5WrapMacroTest +) +add_executable(Qt5WrapMacroTest WIN32 main_wrap_test.cpp ${moc_file}) +target_include_directories(Qt5WrapMacroTest PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/interface") +target_link_libraries(Qt5WrapMacroTest Qt5::Core) diff --git a/tests/auto/cmake/test_moc_macro_target/interface/myinterface.h b/tests/auto/cmake/test_moc_macro_target/interface/myinterface.h new file mode 100644 index 0000000000..7218b200dd --- /dev/null +++ b/tests/auto/cmake/test_moc_macro_target/interface/myinterface.h @@ -0,0 +1,52 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Stephen Kelly <stephen.kelly@kdab.com> +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MYINTERFACE_H +#define MYINTERFACE_H + +class MyInterface +{ + +}; + +Q_DECLARE_INTERFACE(MyInterface, "org.cmake.example.MyInterface") + +#endif diff --git a/tests/auto/cmake/test_moc_macro_target/main_gen_test.cpp b/tests/auto/cmake/test_moc_macro_target/main_gen_test.cpp new file mode 100644 index 0000000000..bdedc4e485 --- /dev/null +++ b/tests/auto/cmake/test_moc_macro_target/main_gen_test.cpp @@ -0,0 +1,61 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Stephen Kelly <stephen.kelly@kdab.com> +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QObject> + +#include "myinterface.h" + +class MyObject : public QObject, MyInterface +{ + Q_OBJECT + Q_INTERFACES(MyInterface) +public: + explicit MyObject(QObject *parent = 0) : QObject(parent) { } +}; + +int main(int argc, char **argv) +{ + MyObject mo; + mo.objectName(); + return 0; +} + +#include "main_gen_test.moc" diff --git a/tests/auto/cmake/test_moc_macro_target/main_wrap_test.cpp b/tests/auto/cmake/test_moc_macro_target/main_wrap_test.cpp new file mode 100644 index 0000000000..763e21b5d9 --- /dev/null +++ b/tests/auto/cmake/test_moc_macro_target/main_wrap_test.cpp @@ -0,0 +1,51 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Stephen Kelly <stephen.kelly@kdab.com> +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QObject> + +#include "mywrapobject.h" + +int main(int argc, char **argv) +{ + MyWrapObject mwo; + mwo.objectName(); + return 0; +} diff --git a/tests/auto/cmake/test_moc_macro_target/mywrapobject.h b/tests/auto/cmake/test_moc_macro_target/mywrapobject.h new file mode 100644 index 0000000000..29e9b24556 --- /dev/null +++ b/tests/auto/cmake/test_moc_macro_target/mywrapobject.h @@ -0,0 +1,57 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Stephen Kelly <stephen.kelly@kdab.com> +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite 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 Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/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 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MYWRAPOBJECT_H +#define MYWRAPOBJECT_H + +#include <QObject> + +#include "myinterface.h" + +class MyWrapObject : public QObject, MyInterface +{ + Q_OBJECT + Q_INTERFACES(MyInterface) +public: + explicit MyWrapObject(QObject *parent = 0) : QObject(parent) { } +}; + +#endif diff --git a/tests/auto/corelib/kernel/qobject/signalbug/signalbug.pro b/tests/auto/corelib/kernel/qobject/signalbug/signalbug.pro index 0dc7903c4c..8823d54590 100644 --- a/tests/auto/corelib/kernel/qobject/signalbug/signalbug.pro +++ b/tests/auto/corelib/kernel/qobject/signalbug/signalbug.pro @@ -1,7 +1,7 @@ CONFIG -= app_bundle debug_and_release CONFIG += console DESTDIR = ./ -QT -= gui +QT = core wince*: { LIBS += coredll.lib } diff --git a/tests/auto/corelib/plugin/qlibrary/qlibrary.pro b/tests/auto/corelib/plugin/qlibrary/qlibrary.pro index 49c29d7edc..5bdf780fc0 100644 --- a/tests/auto/corelib/plugin/qlibrary/qlibrary.pro +++ b/tests/auto/corelib/plugin/qlibrary/qlibrary.pro @@ -1,4 +1,4 @@ -QT -= gui +QT = core TEMPLATE = subdirs CONFIG += ordered diff --git a/tests/auto/dbus/qdbusabstractadaptor/qmyserver/qmyserver.pro b/tests/auto/dbus/qdbusabstractadaptor/qmyserver/qmyserver.pro index 59597abe7b..dc480fc88c 100644 --- a/tests/auto/dbus/qdbusabstractadaptor/qmyserver/qmyserver.pro +++ b/tests/auto/dbus/qdbusabstractadaptor/qmyserver/qmyserver.pro @@ -1,7 +1,6 @@ SOURCES = qmyserver.cpp HEADERS = ../myobject.h TARGET = qmyserver -QT += dbus -QT -= gui +QT = core dbus CONFIG -= app_bundle DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/dbus/qdbusabstractinterface/qpinger/qpinger.pro b/tests/auto/dbus/qdbusabstractinterface/qpinger/qpinger.pro index 605b52e3aa..b863135b68 100644 --- a/tests/auto/dbus/qdbusabstractinterface/qpinger/qpinger.pro +++ b/tests/auto/dbus/qdbusabstractinterface/qpinger/qpinger.pro @@ -1,6 +1,5 @@ SOURCES = qpinger.cpp ../interface.cpp HEADERS = ../interface.h TARGET = qpinger -QT += dbus -QT -= gui +QT = core dbus DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/dbus/qdbusinterface/qmyserver/qmyserver.pro b/tests/auto/dbus/qdbusinterface/qmyserver/qmyserver.pro index 59597abe7b..dc480fc88c 100644 --- a/tests/auto/dbus/qdbusinterface/qmyserver/qmyserver.pro +++ b/tests/auto/dbus/qdbusinterface/qmyserver/qmyserver.pro @@ -1,7 +1,6 @@ SOURCES = qmyserver.cpp HEADERS = ../myobject.h TARGET = qmyserver -QT += dbus -QT -= gui +QT = core dbus CONFIG -= app_bundle DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/dbus/qdbusmarshall/qpong/qpong.pro b/tests/auto/dbus/qdbusmarshall/qpong/qpong.pro index a63e915d9a..d652036034 100644 --- a/tests/auto/dbus/qdbusmarshall/qpong/qpong.pro +++ b/tests/auto/dbus/qdbusmarshall/qpong/qpong.pro @@ -1,7 +1,5 @@ SOURCES = qpong.cpp TARGET = qpong -QT += dbus -QT -= gui - +QT = core dbus DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/network/access/qabstractnetworkcache/qabstractnetworkcache.pro b/tests/auto/network/access/qabstractnetworkcache/qabstractnetworkcache.pro index 56572a2490..2b5ffab088 100644 --- a/tests/auto/network/access/qabstractnetworkcache/qabstractnetworkcache.pro +++ b/tests/auto/network/access/qabstractnetworkcache/qabstractnetworkcache.pro @@ -1,8 +1,7 @@ CONFIG += testcase CONFIG += parallel_test TARGET = tst_qabstractnetworkcache -QT += network testlib -QT -= gui +QT = core network testlib SOURCES += tst_qabstractnetworkcache.cpp TESTDATA += tests/* diff --git a/tests/auto/network/access/qnetworkcachemetadata/qnetworkcachemetadata.pro b/tests/auto/network/access/qnetworkcachemetadata/qnetworkcachemetadata.pro index ebef3b007d..7342252963 100644 --- a/tests/auto/network/access/qnetworkcachemetadata/qnetworkcachemetadata.pro +++ b/tests/auto/network/access/qnetworkcachemetadata/qnetworkcachemetadata.pro @@ -1,7 +1,6 @@ CONFIG += testcase CONFIG += parallel_test TARGET = tst_qnetworkcachemetadata -QT -= gui -QT += network testlib +QT = core network testlib SOURCES += tst_qnetworkcachemetadata.cpp DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/network/access/qnetworkdiskcache/qnetworkdiskcache.pro b/tests/auto/network/access/qnetworkdiskcache/qnetworkdiskcache.pro index d84a332870..57f9c0534a 100644 --- a/tests/auto/network/access/qnetworkdiskcache/qnetworkdiskcache.pro +++ b/tests/auto/network/access/qnetworkdiskcache/qnetworkdiskcache.pro @@ -1,7 +1,6 @@ CONFIG += testcase CONFIG += parallel_test TARGET = tst_qnetworkdiskcache -QT -= gui -QT += network testlib +QT = core network testlib SOURCES += tst_qnetworkdiskcache.cpp DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/network/ssl/qsslsocket/qsslsocket.pro b/tests/auto/network/ssl/qsslsocket/qsslsocket.pro index f799d180cd..d8a6b2cdcb 100644 --- a/tests/auto/network/ssl/qsslsocket/qsslsocket.pro +++ b/tests/auto/network/ssl/qsslsocket/qsslsocket.pro @@ -2,8 +2,7 @@ CONFIG += testcase SOURCES += tst_qsslsocket.cpp !wince*:win32:LIBS += -lws2_32 -QT += core-private network-private testlib -QT -= gui +QT = core core-private network-private testlib TARGET = tst_qsslsocket diff --git a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/qsslsocket_onDemandCertificates_member.pro b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/qsslsocket_onDemandCertificates_member.pro index 1626b62286..e8247d7b16 100644 --- a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/qsslsocket_onDemandCertificates_member.pro +++ b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/qsslsocket_onDemandCertificates_member.pro @@ -4,8 +4,7 @@ testcase.timeout = 300 # this test is slow SOURCES += tst_qsslsocket_onDemandCertificates_member.cpp !wince*:win32:LIBS += -lws2_32 -QT += core-private network-private testlib -QT -= gui +QT = core core-private network-private testlib TARGET = tst_qsslsocket_onDemandCertificates_member diff --git a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/qsslsocket_onDemandCertificates_static.pro b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/qsslsocket_onDemandCertificates_static.pro index 06fad48d5a..8a95e11780 100644 --- a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/qsslsocket_onDemandCertificates_static.pro +++ b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/qsslsocket_onDemandCertificates_static.pro @@ -3,8 +3,7 @@ CONFIG += parallel_test SOURCES += tst_qsslsocket_onDemandCertificates_static.cpp !wince*:win32:LIBS += -lws2_32 -QT += core-private network-private testlib -QT -= gui +QT = core core-private network-private testlib TARGET = tst_qsslsocket_onDemandCertificates_static diff --git a/tests/auto/tools/moc/moc.pro b/tests/auto/tools/moc/moc.pro index 1600c458b5..5ea8c06f02 100644 --- a/tests/auto/tools/moc/moc.pro +++ b/tests/auto/tools/moc/moc.pro @@ -29,8 +29,7 @@ if(*-g++*|*-icc*|*-clang*|*-llvm):!irix-*:!win32-*: HEADERS += os9-newlines.h wi if(*-g++*|*-clang*): HEADERS += dollars.h SOURCES += tst_moc.cpp -QT -= gui -QT += sql network testlib +QT = core sql network testlib qtHaveModule(dbus) { DEFINES += WITH_DBUS QT += dbus diff --git a/tests/auto/tools/moc/tst_moc.cpp b/tests/auto/tools/moc/tst_moc.cpp index e7303d716e..a6cd85ade5 100644 --- a/tests/auto/tools/moc/tst_moc.cpp +++ b/tests/auto/tools/moc/tst_moc.cpp @@ -566,6 +566,7 @@ private slots: void parseDefines(); void preprocessorOnly(); void unterminatedFunctionMacro(); + void QTBUG32933_relatedObjectsDontIncludeItself(); signals: void sigWithUnsignedArg(unsigned foo); @@ -1759,6 +1760,14 @@ void tst_Moc::warnings_data() << 1 << QString() << QString("standard input:1: Error: Class contains Q_OBJECT macro but does not inherit from QObject"); + + QTest::newRow("Warning on invalid macro") + << QByteArray("#define Foo(a, b)\n class X : public QObject { Q_OBJECT }; \n Foo(a) \n Foo(a,b,c) \n") + << QStringList() + << 0 + << QString("IGNORE_ALL_STDOUT") + << QString(":3: Warning: Macro argument mismatch.\n:4: Warning: Macro argument mismatch."); + } void tst_Moc::warnings() @@ -1800,7 +1809,7 @@ void tst_Moc::warnings() // magic value "IGNORE_ALL_STDOUT" ignores stdout if (expectedStdOut != "IGNORE_ALL_STDOUT") QCOMPARE(QString::fromLocal8Bit(proc.readAllStandardOutput()).trimmed(), expectedStdOut); - QCOMPARE(QString::fromLocal8Bit(proc.readAllStandardError()).trimmed(), expectedStdErr); + QCOMPARE(QString::fromLocal8Bit(proc.readAllStandardError()).trimmed().remove('\r'), expectedStdErr); } class tst_Moc::PrivateClass : public QObject { @@ -3038,7 +3047,37 @@ void tst_Moc::unterminatedFunctionMacro() #endif } +namespace QTBUG32933_relatedObjectsDontIncludeItself { + namespace NS { + class Obj : QObject { + Q_OBJECT + Q_PROPERTY(MyEnum p1 MEMBER member) + Q_PROPERTY(Obj::MyEnum p2 MEMBER member) + Q_PROPERTY(NS::Obj::MyEnum p3 MEMBER member) + Q_PROPERTY(QTBUG32933_relatedObjectsDontIncludeItself::NS::Obj::MyEnum p4 MEMBER member) + Q_ENUMS(MyEnum); + public: + enum MyEnum { Something, SomethingElse }; + MyEnum member; + }; + } +} + +void tst_Moc::QTBUG32933_relatedObjectsDontIncludeItself() +{ + const QMetaObject *mo = &QTBUG32933_relatedObjectsDontIncludeItself::NS::Obj::staticMetaObject; + const QMetaObject **objects = mo->d.relatedMetaObjects; + // the related objects should be empty because the enums is in the same object. + QVERIFY(!objects); + +} + QTEST_MAIN(tst_Moc) +// the generated code must compile with QT_NO_KEYWORDS +#undef signals +#undef slots +#undef emit + #include "tst_moc.moc" diff --git a/tests/auto/widgets/itemviews/qcolumnview/tst_qcolumnview.cpp b/tests/auto/widgets/itemviews/qcolumnview/tst_qcolumnview.cpp index c17e2523f9..d3191b2206 100644 --- a/tests/auto/widgets/itemviews/qcolumnview/tst_qcolumnview.cpp +++ b/tests/auto/widgets/itemviews/qcolumnview/tst_qcolumnview.cpp @@ -419,12 +419,15 @@ void tst_QColumnView::scrollTo() QWidget w; w.show(); + QCOMPARE(view.HorizontalOffset(), 0); if (giveFocus) view.setFocus(Qt::OtherFocusReason); else view.clearFocus(); + QCOMPARE(view.HorizontalOffset(), 0); qApp->processEvents(); + QCOMPARE(view.HorizontalOffset(), 0); QTRY_COMPARE(view.hasFocus(), giveFocus); // scroll to the right int level = 0; @@ -440,10 +443,8 @@ void tst_QColumnView::scrollTo() if (level >= 2) { if (!reverse) { QTRY_VERIFY(view.HorizontalOffset() < 0); - if (last <= view.HorizontalOffset()) { - qDebug() << "Test failure. last=" << last + qDebug() << "last=" << last << " ; HorizontalOffset= " << view.HorizontalOffset(); - } QTRY_VERIFY(last > view.HorizontalOffset()); } else { QTRY_VERIFY(view.HorizontalOffset() > 0); diff --git a/tests/auto/xml/dom/qdom/qdom.pro b/tests/auto/xml/dom/qdom/qdom.pro index db19a8ba89..3248b8e0e2 100644 --- a/tests/auto/xml/dom/qdom/qdom.pro +++ b/tests/auto/xml/dom/qdom/qdom.pro @@ -3,7 +3,6 @@ TARGET = tst_qdom SOURCES += tst_qdom.cpp QT = core xml testlib -QT -= gui wince* { wince*|qt_not_deployed { diff --git a/tests/auto/xml/sax/qxmlinputsource/qxmlinputsource.pro b/tests/auto/xml/sax/qxmlinputsource/qxmlinputsource.pro index a8bf834074..8846ae5e4a 100644 --- a/tests/auto/xml/sax/qxmlinputsource/qxmlinputsource.pro +++ b/tests/auto/xml/sax/qxmlinputsource/qxmlinputsource.pro @@ -1,7 +1,4 @@ CONFIG += testcase TARGET = tst_qxmlinputsource SOURCES += tst_qxmlinputsource.cpp -QT += core xml network testlib -QT -= gui - - +QT = core xml network testlib diff --git a/tests/auto/xml/sax/qxmlsimplereader/qxmlsimplereader.pro b/tests/auto/xml/sax/qxmlsimplereader/qxmlsimplereader.pro index 981f506c6d..349b976f58 100644 --- a/tests/auto/xml/sax/qxmlsimplereader/qxmlsimplereader.pro +++ b/tests/auto/xml/sax/qxmlsimplereader/qxmlsimplereader.pro @@ -6,7 +6,6 @@ HEADERS += parser/parser.h SOURCES += tst_qxmlsimplereader.cpp parser/parser.cpp CONFIG += no_batch -QT += network xml testlib -QT -= gui +QT = core network xml testlib TESTDATA += encodings/* xmldocs/* |