Merge "Merge remote-tracking branch 'origin/stable' into dev" into refs/staging/dev

This commit is contained in:
Sergio Ahumada 2013-09-02 15:07:53 +02:00 committed by The Qt Project
commit 0a3eb0fe44
126 changed files with 2001 additions and 4679 deletions

2
configure vendored
View File

@ -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

View File

@ -7,6 +7,7 @@ SUBDIRS = \
gestures \
gui \
ipc \
json \
network \
opengl \
qpa \

2
examples/json/json.pro Normal file
View File

@ -0,0 +1,2 @@
TEMPLATE = subdirs
SUBDIRS = savegame

View File

@ -38,45 +38,64 @@
**
****************************************************************************/
#include <QtWidgets>
#include "finddialog.h"
#include "character.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()));
Character::Character() :
mLevel(0),
mClassType(Warrior) {
}
void FindDialog::findClicked()
Character::Character(const QString &name, int level, Character::ClassType classType) :
mName(name),
mLevel(level),
mClassType(classType)
{
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()
QString Character::name() const
{
return findText;
return mName;
}
void Character::setName(const QString &name)
{
mName = name;
}
int Character::level() const
{
return mLevel;
}
void Character::setLevel(int level)
{
mLevel = level;
}
Character::ClassType Character::classType() const
{
return mClassType;
}
void Character::setClassType(Character::ClassType classType)
{
mClassType = classType;
}
//! [0]
void Character::read(const QJsonObject &json)
{
mName = json["name"].toString();
mLevel = json["level"].toDouble();
mClassType = ClassType(qRound(json["classType"].toDouble()));
}
//! [0]
//! [1]
void Character::write(QJsonObject &json) const
{
json["name"] = mName;
json["level"] = mLevel;
json["classType"] = mClassType;
}
//! [1]

View File

@ -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
};
public slots:
void findClicked();
Character();
Character(const QString &name, int level, ClassType classType);
QString name() const;
void setName(const QString &name);
int level() const;
void setLevel(int level);
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

View File

@ -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}
*/

View File

@ -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]

View File

@ -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();
public slots:
void findClicked();
enum SaveFormat {
Json, Binary
};
const Character &player() const;
const QList<Level> &levels() const;
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

View File

@ -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);
void Level::setNpcs(const QList<Character> &npcs)
{
mNpcs = npcs;
}
//! [slots]
public slots:
void addContact();
void submitContact();
void cancel();
//! [slots]
//! [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]
//! [pushbutton declaration]
private:
QPushButton *addButton;
QPushButton *submitButton;
QPushButton *cancelButton;
QLineEdit *nameLine;
QTextEdit *addressText;
//! [pushbutton declaration]
//! [remaining private variables]
QMap<QString, QString> contacts;
QString oldName;
QString oldAddress;
};
//! [remaining private variables]
#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]

View File

@ -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

View File

@ -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]

View File

@ -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

File diff suppressed because it is too large Load Diff

View File

@ -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.

View File

@ -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

View File

@ -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]

View File

@ -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]

View File

@ -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)

View File

@ -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]

View File

@ -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]

View File

@ -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)

View File

@ -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]

View File

@ -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

View File

@ -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();
}

View File

@ -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)

View File

@ -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]

View File

@ -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

View File

@ -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)

View File

@ -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;
}
}

View File

@ -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

View File

@ -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]

View File

@ -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

View File

@ -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();
}

View File

@ -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)

View File

@ -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]

View File

@ -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

View File

@ -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();
}

View File

@ -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)

View File

@ -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]

View File

@ -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

View File

@ -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;
}

View File

@ -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();
}

View File

@ -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)

View File

@ -1,2 +1,2 @@
TEMPLATE = subdirs
SUBDIRS += addressbook-fr threads addressbook widgets modelview gettingStarted
SUBDIRS += threads addressbook widgets modelview gettingStarted

View File

@ -19,8 +19,11 @@ SUBDIRS = \
statemachine \
tools \
tutorials \
widgets \
windowcontainer
widgets
contains(QT_CONFIG, opengl(es1|es2)?) {
SUBDIRS += windowcontainer
}
!contains(QT_CONFIG, opengl(es1|es2)?): SUBDIRS -= windowcontainer
contains(DEFINES, QT_NO_CURSOR): SUBDIRS -= mainwindows

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -309,7 +309,8 @@ SOURCES = myclass.cpp \
#! [50]
SUBDIRS = kernel \
tools
tools \
myapp
#! [50]

View File

@ -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:

View File

@ -130,6 +130,11 @@ if (NOT TARGET Qt5::WinMain)
set(_isPolicyNEW $<TARGET_POLICY:CMP0020>)
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>

View File

@ -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)
else()
add_custom_command(OUTPUT ${outfile}
COMMAND ${Qt5Core_MOC_EXECUTABLE}
ARGS ${moc_flags} ${moc_options} -o ${outfile} ${infile}
DEPENDS ${infile} 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()
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)

View File

@ -36,7 +36,8 @@ exampledirs += \
../ \
snippets \
../../../examples/threads/ \
../../../examples/tools/
../../../examples/tools/ \
../../../examples/json/
imagedirs += images

View File

@ -369,4 +369,6 @@
\li The items (T)
\endlist
\endtable
\sa {JSON Support in Qt}
*/

View File

@ -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

View File

@ -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

View File

@ -1167,6 +1167,13 @@ bool qSharedBuild() Q_DECL_NOTHROW
Defined on Linux.
*/
/*!
\macro Q_OS_ANDROID
\relates <QtGlobal>
Defined on Android.
*/
/*!
\macro Q_OS_FREEBSD
\relates <QtGlobal>

View File

@ -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

View File

@ -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}
*/
/*!

View File

@ -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}
*/
/*!

View File

@ -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

View File

@ -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}
*/
/*!

View File

@ -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}
*/
/*!

View File

@ -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":

View File

@ -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;
}

View File

@ -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)

View File

@ -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>

View File

@ -97,6 +97,11 @@ void QBackingStore::flush(const QRegion &region, 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) {

View File

@ -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;

View File

@ -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);
}
QImage qt_renderDistanceFieldGlyph(const QRawFont &font, glyph_t glyph, bool doubleResolution)
QDistanceField::QDistanceField(int width, int height)
: d(QDistanceFieldData::create(QSize(width, height)))
{
}
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

View File

@ -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

View File

@ -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);
}

View File

@ -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);
// 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;
QNetworkInterfacePrivate *iface = new QNetworkInterfacePrivate;
interfaces << iface;
iface->index = ifindex;
iface->name = QString::fromLatin1(ptr->ifa_name);
iface->flags = convertFlags(ptr->ifa_flags);
if ( ptr->ifa_addr->sa_family == AF_PACKET ) {
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);
seenInterfaces.insert(iface->name);
}
}
// 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;
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;

View File

@ -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

View File

@ -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);
}

View File

@ -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

View File

@ -69,7 +69,6 @@ void QAndroidOpenGLPlatformWindow::invalidateSurface()
{
QWindowSystemInterface::handleExposeEvent(window(), QRegion()); // Obscure event
QWindowSystemInterface::flushWindowSystemEvents();
QEglFSWindow::invalidateSurface();
m_window = 0;
m_surface = 0;

View File

@ -594,6 +594,7 @@ void QCocoaEventDispatcherPrivate::temporarilyStopAllModalSessions()
if (info.session) {
[NSApp endModalSession:info.session];
info.session = 0;
[(NSWindow*) info.nswindow release];
}
}
currentModalSessionCached = 0;

View File

@ -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
{

View File

@ -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"]) {

View File

@ -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;
}

View File

@ -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);
}

View File

@ -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;

View File

@ -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);
}

View File

@ -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));
#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);
#else
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);
data.name = QString::fromWCharArray(info.szDevice);
if (data.name == QLatin1String("WinDisc")) {
data.flags |= QWindowsScreenData::LockScreen;
} else {
qWarning("%s: Unable to obtain handle for monitor '%s', defaulting to %g DPI.",
__FUNCTION__, qPrintable(QString::fromWCharArray(info.szDevice)),
data.dpi.first);
}
#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);
#else
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 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;
}

View File

@ -59,7 +59,8 @@ struct QWindowsScreenData
enum Flags
{
PrimaryScreen = 0x1,
VirtualDesktop = 0x2
VirtualDesktop = 0x2,
LockScreen = 0x4 // Temporary screen existing during user change, etc.
};
QWindowsScreenData();

View File

@ -549,6 +549,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);
@ -962,7 +974,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;
@ -1483,14 +1495,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;

View File

@ -230,6 +230,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();
@ -376,6 +377,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)

View File

@ -306,6 +306,10 @@ void QXcbBackingStore::flush(QWindow *window, const QRegion &region, 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)

View File

@ -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)

View File

@ -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

View File

@ -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");

View File

@ -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);

View File

@ -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".
*/

View File

@ -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
@ -272,15 +274,31 @@ associated with the \e .cpp source files.
Add the specified directories to the list of directories containing the \e .cpp and
\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 \

View File

@ -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);

View File

@ -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),

View File

@ -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();
}
}
}
}

View File

@ -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()

View File

@ -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)

Some files were not shown because too many files have changed in this diff Show More