diff options
author | Jørgen Lind <jorgen.lind@nokia.com> | 2011-06-27 12:27:54 +0200 |
---|---|---|
committer | Jørgen Lind <jorgen.lind@nokia.com> | 2011-06-27 12:27:54 +0200 |
commit | 18a3f6169bb8a763366003d92b8013950578c79f (patch) | |
tree | e39fa00a9511410fea9be35a6130007e43719ad8 /examples/sql | |
parent | 371d398f70e10408e0eaba7b5f05e638a0048599 (diff) | |
parent | a06c8405d053b16327d65415f3335eceb37abd3b (diff) |
Merge remote-tracking branch 'base/master' into refactor
Conflicts:
demos/demos.pro
demos/embedded/digiflip/digiflip.pro
examples/examples.pro
examples/graphicsview/embeddeddialogs/embeddeddialogs.pro
src/gui/kernel/qplatformglcontext_qpa.cpp
src/plugins/platforms/wayland/gl_integration/xcomposite_egl/qwaylandxcompositeeglcontext.cpp
src/plugins/platforms/wayland/gl_integration/xcomposite_glx/qwaylandxcompositeglxcontext.cpp
src/plugins/platforms/wayland/qwaylanddisplay.cpp
src/plugins/platforms/wayland/qwaylandwindow.cpp
Change-Id: I2a4ec9e2ca9c9aa9d57b55f98985e810b77bb745
Diffstat (limited to 'examples/sql')
21 files changed, 2067 insertions, 1 deletions
diff --git a/examples/sql/books/bookdelegate.cpp b/examples/sql/books/bookdelegate.cpp new file mode 100644 index 0000000000..a4cf5d3a26 --- /dev/null +++ b/examples/sql/books/bookdelegate.cpp @@ -0,0 +1,126 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "bookdelegate.h" + +#include <QtWidgets> + +BookDelegate::BookDelegate(QObject *parent) + : QSqlRelationalDelegate(parent), star(QPixmap(":images/star.png")) +{ +} + +void BookDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const +{ + if (index.column() != 5) { + QStyleOptionViewItemV3 opt = option; + opt.rect.adjust(0, 0, -1, -1); // since we draw the grid ourselves + QSqlRelationalDelegate::paint(painter, opt, index); + } else { + const QAbstractItemModel *model = index.model(); + QPalette::ColorGroup cg = (option.state & QStyle::State_Enabled) ? + (option.state & QStyle::State_Active) ? QPalette::Normal : QPalette::Inactive : QPalette::Disabled; + + if (option.state & QStyle::State_Selected) + painter->fillRect(option.rect, option.palette.color(cg, QPalette::Highlight)); + + int rating = model->data(index, Qt::DisplayRole).toInt(); + int width = star.width(); + int height = star.height(); + int x = option.rect.x(); + int y = option.rect.y() + (option.rect.height() / 2) - (height / 2); + for (int i = 0; i < rating; ++i) { + painter->drawPixmap(x, y, star); + x += width; + } + drawFocus(painter, option, option.rect.adjusted(0, 0, -1, -1)); // since we draw the grid ourselves + } + + QPen pen = painter->pen(); + painter->setPen(option.palette.color(QPalette::Mid)); + painter->drawLine(option.rect.bottomLeft(), option.rect.bottomRight()); + painter->drawLine(option.rect.topRight(), option.rect.bottomRight()); + painter->setPen(pen); +} + +QSize BookDelegate::sizeHint(const QStyleOptionViewItem &option, + const QModelIndex &index) const +{ + if (index.column() == 5) + return QSize(5 * star.width(), star.height()) + QSize(1, 1); + + return QSqlRelationalDelegate::sizeHint(option, index) + QSize(1, 1); // since we draw the grid ourselves +} + +bool BookDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, + const QStyleOptionViewItem &option, + const QModelIndex &index) +{ + if (index.column() != 5) + return QSqlRelationalDelegate::editorEvent(event, model, option, index); + + if (event->type() == QEvent::MouseButtonPress) { + QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event); + int stars = qBound(0, int(0.7 + qreal(mouseEvent->pos().x() + - option.rect.x()) / star.width()), 5); + model->setData(index, QVariant(stars)); + return false; //so that the selection can change + } + + return true; +} + +QWidget *BookDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, + const QModelIndex &index) const +{ + if (index.column() != 4) + return QSqlRelationalDelegate::createEditor(parent, option, index); + + // for editing the year, return a spinbox with a range from -1000 to 2100. + QSpinBox *sb = new QSpinBox(parent); + sb->setFrame(false); + sb->setMaximum(2100); + sb->setMinimum(-1000); + + return sb; +} + diff --git a/examples/sql/books/bookdelegate.h b/examples/sql/books/bookdelegate.h new file mode 100644 index 0000000000..5dc39c0223 --- /dev/null +++ b/examples/sql/books/bookdelegate.h @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef BOOKDELEGATE_H +#define BOOKDELEGATE_H + +#include <QModelIndex> +#include <QPixmap> +#include <QSize> +#include <QSqlRelationalDelegate> + +QT_FORWARD_DECLARE_CLASS(QPainter) + +class BookDelegate : public QSqlRelationalDelegate +{ +public: + BookDelegate(QObject *parent); + + void paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index) const; + + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; + + bool editorEvent(QEvent *event, QAbstractItemModel *model, + const QStyleOptionViewItem &option, + const QModelIndex &index); + + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, + const QModelIndex &index) const; + +private: + QPixmap star; +}; + +#endif diff --git a/examples/sql/books/books.pro b/examples/sql/books/books.pro new file mode 100644 index 0000000000..316e2d9372 --- /dev/null +++ b/examples/sql/books/books.pro @@ -0,0 +1,23 @@ +TEMPLATE = app +INCLUDEPATH += . + +HEADERS = bookdelegate.h bookwindow.h initdb.h +RESOURCES = books.qrc +SOURCES = bookdelegate.cpp main.cpp bookwindow.cpp +FORMS = bookwindow.ui + +QT += sql widgets widgets + +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/sql/books +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS *.pro images +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/sql/books +INSTALLS += target sources + +symbian: CONFIG += qt_example + +wince*: { + CONFIG(debug, debug|release):sqlPlugins.files = $$QT_BUILD_TREE/plugins/sqldrivers/*d4.dll + CONFIG(release, debug|release):sqlPlugins.files = $$QT_BUILD_TREE/plugins/sqldrivers/*[^d]4.dll + sqlPlugins.path = sqldrivers + DEPLOYMENT += sqlPlugins +} diff --git a/examples/sql/books/books.qrc b/examples/sql/books/books.qrc new file mode 100644 index 0000000000..342638ecb0 --- /dev/null +++ b/examples/sql/books/books.qrc @@ -0,0 +1,5 @@ +<!DOCTYPE RCC><RCC version="1.0"> +<qresource prefix="/"> + <file>images/star.png</file> +</qresource> +</RCC> diff --git a/examples/sql/books/bookwindow.cpp b/examples/sql/books/bookwindow.cpp new file mode 100644 index 0000000000..40d23d1761 --- /dev/null +++ b/examples/sql/books/bookwindow.cpp @@ -0,0 +1,121 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "bookwindow.h" +#include "bookdelegate.h" +#include "initdb.h" + +#include <QtSql> + +BookWindow::BookWindow() +{ + ui.setupUi(this); + + if (!QSqlDatabase::drivers().contains("QSQLITE")) + QMessageBox::critical(this, "Unable to load database", "This demo needs the SQLITE driver"); + + // initialize the database + QSqlError err = initDb(); + if (err.type() != QSqlError::NoError) { + showError(err); + return; + } + + // Create the data model + model = new QSqlRelationalTableModel(ui.bookTable); + model->setEditStrategy(QSqlTableModel::OnManualSubmit); + model->setTable("books"); + + // Remember the indexes of the columns + authorIdx = model->fieldIndex("author"); + genreIdx = model->fieldIndex("genre"); + + // Set the relations to the other database tables + model->setRelation(authorIdx, QSqlRelation("authors", "id", "name")); + model->setRelation(genreIdx, QSqlRelation("genres", "id", "name")); + + // Set the localized header captions + model->setHeaderData(authorIdx, Qt::Horizontal, tr("Author Name")); + model->setHeaderData(genreIdx, Qt::Horizontal, tr("Genre")); + model->setHeaderData(model->fieldIndex("title"), Qt::Horizontal, tr("Title")); + model->setHeaderData(model->fieldIndex("year"), Qt::Horizontal, tr("Year")); + model->setHeaderData(model->fieldIndex("rating"), Qt::Horizontal, tr("Rating")); + + // Populate the model + if (!model->select()) { + showError(model->lastError()); + return; + } + + // Set the model and hide the ID column + ui.bookTable->setModel(model); + ui.bookTable->setItemDelegate(new BookDelegate(ui.bookTable)); + ui.bookTable->setColumnHidden(model->fieldIndex("id"), true); + ui.bookTable->setSelectionMode(QAbstractItemView::SingleSelection); + + // Initialize the Author combo box + ui.authorEdit->setModel(model->relationModel(authorIdx)); + ui.authorEdit->setModelColumn(model->relationModel(authorIdx)->fieldIndex("name")); + + ui.genreEdit->setModel(model->relationModel(genreIdx)); + ui.genreEdit->setModelColumn(model->relationModel(genreIdx)->fieldIndex("name")); + + QDataWidgetMapper *mapper = new QDataWidgetMapper(this); + mapper->setModel(model); + mapper->setItemDelegate(new BookDelegate(this)); + mapper->addMapping(ui.titleEdit, model->fieldIndex("title")); + mapper->addMapping(ui.yearEdit, model->fieldIndex("year")); + mapper->addMapping(ui.authorEdit, authorIdx); + mapper->addMapping(ui.genreEdit, genreIdx); + mapper->addMapping(ui.ratingEdit, model->fieldIndex("rating")); + + connect(ui.bookTable->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), + mapper, SLOT(setCurrentModelIndex(QModelIndex))); + + ui.bookTable->setCurrentIndex(model->index(0, 0)); +} + +void BookWindow::showError(const QSqlError &err) +{ + QMessageBox::critical(this, "Unable to initialize Database", + "Error initializing database: " + err.text()); +} + diff --git a/examples/sql/books/bookwindow.h b/examples/sql/books/bookwindow.h new file mode 100644 index 0000000000..781a2f8bb3 --- /dev/null +++ b/examples/sql/books/bookwindow.h @@ -0,0 +1,64 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef BOOKWINDOW_H +#define BOOKWINDOW_H + +#include <QtWidgets> +#include <QtSql> + +#include "ui_bookwindow.h" + + +class BookWindow: public QMainWindow +{ + Q_OBJECT +public: + BookWindow(); + +private: + void showError(const QSqlError &err); + Ui::BookWindow ui; + QSqlRelationalTableModel *model; + int authorIdx, genreIdx; +}; + +#endif diff --git a/examples/sql/books/bookwindow.ui b/examples/sql/books/bookwindow.ui new file mode 100644 index 0000000000..659d324564 --- /dev/null +++ b/examples/sql/books/bookwindow.ui @@ -0,0 +1,149 @@ +<ui version="4.0" > + <author></author> + <comment></comment> + <exportmacro></exportmacro> + <class>BookWindow</class> + <widget class="QMainWindow" name="BookWindow" > + <property name="geometry" > + <rect> + <x>0</x> + <y>0</y> + <width>601</width> + <height>420</height> + </rect> + </property> + <property name="windowTitle" > + <string>Books</string> + </property> + <widget class="QWidget" name="centralWidget" > + <layout class="QVBoxLayout" > + <property name="margin" > + <number>9</number> + </property> + <property name="spacing" > + <number>6</number> + </property> + <item> + <widget class="QGroupBox" name="groupBox" > + <property name="title" > + <string>Books</string> + </property> + <layout class="QVBoxLayout" > + <property name="margin" > + <number>9</number> + </property> + <property name="spacing" > + <number>6</number> + </property> + <item> + <widget class="QTableView" name="bookTable" > + <property name="selectionBehavior" > + <enum>QAbstractItemView::SelectRows</enum> + </property> + </widget> + </item> + <item> + <widget class="QGroupBox" name="groupBox_2" > + <property name="title" > + <string>Details</string> + </property> + <layout class="QFormLayout" > + <item row="0" column="0" > + <widget class="QLabel" name="label_5" > + <property name="text" > + <string><b>Title:</b></string> + </property> + </widget> + </item> + <item row="0" column="1" > + <widget class="QLineEdit" name="titleEdit" > + <property name="enabled" > + <bool>true</bool> + </property> + </widget> + </item> + <item row="1" column="0" > + <widget class="QLabel" name="label_2_2_2_2" > + <property name="text" > + <string><b>Author: </b></string> + </property> + </widget> + </item> + <item row="1" column="1" > + <widget class="QComboBox" name="authorEdit" > + <property name="enabled" > + <bool>true</bool> + </property> + </widget> + </item> + <item row="2" column="0" > + <widget class="QLabel" name="label_3" > + <property name="text" > + <string><b>Genre:</b></string> + </property> + </widget> + </item> + <item row="2" column="1" > + <widget class="QComboBox" name="genreEdit" > + <property name="enabled" > + <bool>true</bool> + </property> + </widget> + </item> + <item row="3" column="0" > + <widget class="QLabel" name="label_4" > + <property name="text" > + <string><b>Year:</b></string> + </property> + </widget> + </item> + <item row="3" column="1" > + <widget class="QSpinBox" name="yearEdit" > + <property name="enabled" > + <bool>true</bool> + </property> + <property name="prefix" > + <string/> + </property> + <property name="maximum" > + <number>2100</number> + </property> + <property name="minimum" > + <number>-1000</number> + </property> + </widget> + </item> + <item row="4" column="0" > + <widget class="QLabel" name="label" > + <property name="text" > + <string><b>Rating:</b></string> + </property> + </widget> + </item> + <item row="4" column="1" > + <widget class="QSpinBox" name="ratingEdit" > + <property name="maximum" > + <number>5</number> + </property> + </widget> + </item> + </layout> + </widget> + </item> + </layout> + </widget> + </item> + </layout> + </widget> + </widget> + <pixmapfunction></pixmapfunction> + <tabstops> + <tabstop>bookTable</tabstop> + <tabstop>titleEdit</tabstop> + <tabstop>authorEdit</tabstop> + <tabstop>genreEdit</tabstop> + <tabstop>yearEdit</tabstop> + </tabstops> + <resources/> + <connections/> +</ui> diff --git a/examples/sql/books/images/star.png b/examples/sql/books/images/star.png Binary files differnew file mode 100644 index 0000000000..87f4464bd5 --- /dev/null +++ b/examples/sql/books/images/star.png diff --git a/examples/sql/books/initdb.h b/examples/sql/books/initdb.h new file mode 100644 index 0000000000..9c9bebcba1 --- /dev/null +++ b/examples/sql/books/initdb.h @@ -0,0 +1,125 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef INITDB_H +#define INITDB_H + +#include <QtSql> + +void addBook(QSqlQuery &q, const QString &title, int year, const QVariant &authorId, + const QVariant &genreId, int rating) +{ + q.addBindValue(title); + q.addBindValue(year); + q.addBindValue(authorId); + q.addBindValue(genreId); + q.addBindValue(rating); + q.exec(); +} + +QVariant addGenre(QSqlQuery &q, const QString &name) +{ + q.addBindValue(name); + q.exec(); + return q.lastInsertId(); +} + +QVariant addAuthor(QSqlQuery &q, const QString &name, const QDate &birthdate) +{ + q.addBindValue(name); + q.addBindValue(birthdate); + q.exec(); + return q.lastInsertId(); +} + +QSqlError initDb() +{ + QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); + db.setDatabaseName(":memory:"); + + if (!db.open()) + return db.lastError(); + + QStringList tables = db.tables(); + if (tables.contains("books", Qt::CaseInsensitive) + && tables.contains("authors", Qt::CaseInsensitive)) + return QSqlError(); + + QSqlQuery q; + if (!q.exec(QLatin1String("create table books(id integer primary key, title varchar, author integer, genre integer, year integer, rating integer)"))) + return q.lastError(); + if (!q.exec(QLatin1String("create table authors(id integer primary key, name varchar, birthdate date)"))) + return q.lastError(); + if (!q.exec(QLatin1String("create table genres(id integer primary key, name varchar)"))) + return q.lastError(); + + if (!q.prepare(QLatin1String("insert into authors(name, birthdate) values(?, ?)"))) + return q.lastError(); + QVariant asimovId = addAuthor(q, QLatin1String("Isaac Asimov"), QDate(1920, 2, 1)); + QVariant greeneId = addAuthor(q, QLatin1String("Graham Greene"), QDate(1904, 10, 2)); + QVariant pratchettId = addAuthor(q, QLatin1String("Terry Pratchett"), QDate(1948, 4, 28)); + + if (!q.prepare(QLatin1String("insert into genres(name) values(?)"))) + return q.lastError(); + QVariant sfiction = addGenre(q, QLatin1String("Science Fiction")); + QVariant fiction = addGenre(q, QLatin1String("Fiction")); + QVariant fantasy = addGenre(q, QLatin1String("Fantasy")); + + if (!q.prepare(QLatin1String("insert into books(title, year, author, genre, rating) values(?, ?, ?, ?, ?)"))) + return q.lastError(); + addBook(q, QLatin1String("Foundation"), 1951, asimovId, sfiction, 3); + addBook(q, QLatin1String("Foundation and Empire"), 1952, asimovId, sfiction, 4); + addBook(q, QLatin1String("Second Foundation"), 1953, asimovId, sfiction, 3); + addBook(q, QLatin1String("Foundation's Edge"), 1982, asimovId, sfiction, 3); + addBook(q, QLatin1String("Foundation and Earth"), 1986, asimovId, sfiction, 4); + addBook(q, QLatin1String("Prelude to Foundation"), 1988, asimovId, sfiction, 3); + addBook(q, QLatin1String("Forward the Foundation"), 1993, asimovId, sfiction, 3); + addBook(q, QLatin1String("The Power and the Glory"), 1940, greeneId, fiction, 4); + addBook(q, QLatin1String("The Third Man"), 1950, greeneId, fiction, 5); + addBook(q, QLatin1String("Our Man in Havana"), 1958, greeneId, fiction, 4); + addBook(q, QLatin1String("Guards! Guards!"), 1989, pratchettId, fantasy, 3); + addBook(q, QLatin1String("Night Watch"), 2002, pratchettId, fantasy, 3); + addBook(q, QLatin1String("Going Postal"), 2004, pratchettId, fantasy, 3); + + return QSqlError(); +} + +#endif diff --git a/examples/sql/books/main.cpp b/examples/sql/books/main.cpp new file mode 100644 index 0000000000..e08fb156c3 --- /dev/null +++ b/examples/sql/books/main.cpp @@ -0,0 +1,56 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "bookwindow.h" + +#include <QtWidgets> + +int main(int argc, char * argv[]) +{ + Q_INIT_RESOURCE(books); + + QApplication app(argc, argv); + + BookWindow win; + win.show(); + + return app.exec(); +} diff --git a/examples/sql/sql.pro b/examples/sql/sql.pro index 9c2829d776..68b54e42ca 100644 --- a/examples/sql/sql.pro +++ b/examples/sql/sql.pro @@ -1,6 +1,7 @@ TEMPLATE = subdirs -SUBDIRS = drilldown +SUBDIRS = books \ + drilldown !symbian: SUBDIRS += cachedtable \ relationaltablemodel \ sqlwidgetmapper @@ -11,6 +12,11 @@ SUBDIRS = drilldown querymodel \ tablemodel +!cross_compile:{ + contains(QT_BUILD_PARTS, tools):{ + SUBDIRS += sqlbrowser + } +} # install sources.files = connection.h sql.pro README diff --git a/examples/sql/sqlbrowser/browser.cpp b/examples/sql/sqlbrowser/browser.cpp new file mode 100644 index 0000000000..67ceefd20b --- /dev/null +++ b/examples/sql/sqlbrowser/browser.cpp @@ -0,0 +1,247 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "browser.h" +#include "qsqlconnectiondialog.h" + +#include <QtWidgets> +#include <QtSql> + +Browser::Browser(QWidget *parent) + : QWidget(parent) +{ + setupUi(this); + + table->addAction(insertRowAction); + table->addAction(deleteRowAction); + + if (QSqlDatabase::drivers().isEmpty()) + QMessageBox::information(this, tr("No database drivers found"), + tr("This demo requires at least one Qt database driver. " + "Please check the documentation how to build the " + "Qt SQL plugins.")); + + emit statusMessage(tr("Ready.")); +} + +Browser::~Browser() +{ +} + +void Browser::exec() +{ + QSqlQueryModel *model = new QSqlQueryModel(table); + model->setQuery(QSqlQuery(sqlEdit->toPlainText(), connectionWidget->currentDatabase())); + table->setModel(model); + + if (model->lastError().type() != QSqlError::NoError) + emit statusMessage(model->lastError().text()); + else if (model->query().isSelect()) + emit statusMessage(tr("Query OK.")); + else + emit statusMessage(tr("Query OK, number of affected rows: %1").arg( + model->query().numRowsAffected())); + + updateActions(); +} + +QSqlError Browser::addConnection(const QString &driver, const QString &dbName, const QString &host, + const QString &user, const QString &passwd, int port) +{ + static int cCount = 0; + + QSqlError err; + QSqlDatabase db = QSqlDatabase::addDatabase(driver, QString("Browser%1").arg(++cCount)); + db.setDatabaseName(dbName); + db.setHostName(host); + db.setPort(port); + if (!db.open(user, passwd)) { + err = db.lastError(); + db = QSqlDatabase(); + QSqlDatabase::removeDatabase(QString("Browser%1").arg(cCount)); + } + connectionWidget->refresh(); + + return err; +} + +void Browser::addConnection() +{ + QSqlConnectionDialog dialog(this); + if (dialog.exec() != QDialog::Accepted) + return; + + if (dialog.useInMemoryDatabase()) { + QSqlDatabase::database("in_mem_db", false).close(); + QSqlDatabase::removeDatabase("in_mem_db"); + QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "in_mem_db"); + db.setDatabaseName(":memory:"); + if (!db.open()) + QMessageBox::warning(this, tr("Unable to open database"), tr("An error occurred while " + "opening the connection: ") + db.lastError().text()); + QSqlQuery q("", db); + q.exec("drop table Movies"); + q.exec("drop table Names"); + q.exec("create table Movies (id integer primary key, Title varchar, Director varchar, Rating number)"); + q.exec("insert into Movies values (0, 'Metropolis', 'Fritz Lang', '8.4')"); + q.exec("insert into Movies values (1, 'Nosferatu, eine Symphonie des Grauens', 'F.W. Murnau', '8.1')"); + q.exec("insert into Movies values (2, 'Bis ans Ende der Welt', 'Wim Wenders', '6.5')"); + q.exec("insert into Movies values (3, 'Hardware', 'Richard Stanley', '5.2')"); + q.exec("insert into Movies values (4, 'Mitchell', 'Andrew V. McLaglen', '2.1')"); + q.exec("create table Names (id integer primary key, Firstname varchar, Lastname varchar, City varchar)"); + q.exec("insert into Names values (0, 'Sala', 'Palmer', 'Morristown')"); + q.exec("insert into Names values (1, 'Christopher', 'Walker', 'Morristown')"); + q.exec("insert into Names values (2, 'Donald', 'Duck', 'Andeby')"); + q.exec("insert into Names values (3, 'Buck', 'Rogers', 'Paris')"); + q.exec("insert into Names values (4, 'Sherlock', 'Holmes', 'London')"); + connectionWidget->refresh(); + } else { + QSqlError err = addConnection(dialog.driverName(), dialog.databaseName(), dialog.hostName(), + dialog.userName(), dialog.password(), dialog.port()); + if (err.type() != QSqlError::NoError) + QMessageBox::warning(this, tr("Unable to open database"), tr("An error occurred while " + "opening the connection: ") + err.text()); + } +} + +void Browser::showTable(const QString &t) +{ + QSqlTableModel *model = new QSqlTableModel(table, connectionWidget->currentDatabase()); + model->setEditStrategy(QSqlTableModel::OnRowChange); + model->setTable(connectionWidget->currentDatabase().driver()->escapeIdentifier(t, QSqlDriver::TableName)); + model->select(); + if (model->lastError().type() != QSqlError::NoError) + emit statusMessage(model->lastError().text()); + table->setModel(model); + table->setEditTriggers(QAbstractItemView::DoubleClicked|QAbstractItemView::EditKeyPressed); + + connect(table->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), + this, SLOT(currentChanged())); + updateActions(); +} + +void Browser::showMetaData(const QString &t) +{ + QSqlRecord rec = connectionWidget->currentDatabase().record(t); + QStandardItemModel *model = new QStandardItemModel(table); + + model->insertRows(0, rec.count()); + model->insertColumns(0, 7); + + model->setHeaderData(0, Qt::Horizontal, "Fieldname"); + model->setHeaderData(1, Qt::Horizontal, "Type"); + model->setHeaderData(2, Qt::Horizontal, "Length"); + model->setHeaderData(3, Qt::Horizontal, "Precision"); + model->setHeaderData(4, Qt::Horizontal, "Required"); + model->setHeaderData(5, Qt::Horizontal, "AutoValue"); + model->setHeaderData(6, Qt::Horizontal, "DefaultValue"); + + + for (int i = 0; i < rec.count(); ++i) { + QSqlField fld = rec.field(i); + model->setData(model->index(i, 0), fld.name()); + model->setData(model->index(i, 1), fld.typeID() == -1 + ? QString(QVariant::typeToName(fld.type())) + : QString("%1 (%2)").arg(QVariant::typeToName(fld.type())).arg(fld.typeID())); + model->setData(model->index(i, 2), fld.length()); + model->setData(model->index(i, 3), fld.precision()); + model->setData(model->index(i, 4), fld.requiredStatus() == -1 ? QVariant("?") + : QVariant(bool(fld.requiredStatus()))); + model->setData(model->index(i, 5), fld.isAutoValue()); + model->setData(model->index(i, 6), fld.defaultValue()); + } + + table->setModel(model); + table->setEditTriggers(QAbstractItemView::NoEditTriggers); + + updateActions(); +} + +void Browser::insertRow() +{ + QSqlTableModel *model = qobject_cast<QSqlTableModel *>(table->model()); + if (!model) + return; + + QModelIndex insertIndex = table->currentIndex(); + int row = insertIndex.row() == -1 ? 0 : insertIndex.row(); + model->insertRow(row); + insertIndex = model->index(row, 0); + table->setCurrentIndex(insertIndex); + table->edit(insertIndex); +} + +void Browser::deleteRow() +{ + QSqlTableModel *model = qobject_cast<QSqlTableModel *>(table->model()); + if (!model) + return; + + model->setEditStrategy(QSqlTableModel::OnManualSubmit); + + QModelIndexList currentSelection = table->selectionModel()->selectedIndexes(); + for (int i = 0; i < currentSelection.count(); ++i) { + if (currentSelection.at(i).column() != 0) + continue; + model->removeRow(currentSelection.at(i).row()); + } + + model->submitAll(); + model->setEditStrategy(QSqlTableModel::OnRowChange); + + updateActions(); +} + +void Browser::updateActions() +{ + bool enableIns = qobject_cast<QSqlTableModel *>(table->model()); + bool enableDel = enableIns && table->currentIndex().isValid(); + + insertRowAction->setEnabled(enableIns); + deleteRowAction->setEnabled(enableDel); +} + +void Browser::about() +{ + QMessageBox::about(this, tr("About"), tr("The SQL Browser demonstration " + "shows how a data browser can be used to visualize the results of SQL" + "statements on a live database")); +} diff --git a/examples/sql/sqlbrowser/browser.h b/examples/sql/sqlbrowser/browser.h new file mode 100644 index 0000000000..11f9e36211 --- /dev/null +++ b/examples/sql/sqlbrowser/browser.h @@ -0,0 +1,99 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef BROWSER_H +#define BROWSER_H + +#include <QWidget> +#include "ui_browserwidget.h" + +class ConnectionWidget; +QT_FORWARD_DECLARE_CLASS(QTableView) +QT_FORWARD_DECLARE_CLASS(QPushButton) +QT_FORWARD_DECLARE_CLASS(QTextEdit) +QT_FORWARD_DECLARE_CLASS(QSqlError) + +class Browser: public QWidget, private Ui::Browser +{ + Q_OBJECT +public: + Browser(QWidget *parent = 0); + virtual ~Browser(); + + QSqlError addConnection(const QString &driver, const QString &dbName, const QString &host, + const QString &user, const QString &passwd, int port = -1); + + void insertRow(); + void deleteRow(); + void updateActions(); + +public slots: + void exec(); + void showTable(const QString &table); + void showMetaData(const QString &table); + void addConnection(); + void currentChanged() { updateActions(); } + void about(); + + void on_insertRowAction_triggered() + { insertRow(); } + void on_deleteRowAction_triggered() + { deleteRow(); } + void on_connectionWidget_tableActivated(const QString &table) + { showTable(table); } + void on_connectionWidget_metaDataRequested(const QString &table) + { showMetaData(table); } + void on_submitButton_clicked() + { + exec(); + sqlEdit->setFocus(); + } + void on_clearButton_clicked() + { + sqlEdit->clear(); + sqlEdit->setFocus(); + } + +signals: + void statusMessage(const QString &message); +}; + +#endif diff --git a/examples/sql/sqlbrowser/browserwidget.ui b/examples/sql/sqlbrowser/browserwidget.ui new file mode 100644 index 0000000000..20946f0ede --- /dev/null +++ b/examples/sql/sqlbrowser/browserwidget.ui @@ -0,0 +1,199 @@ +<ui version="4.0" > + <author></author> + <comment></comment> + <exportmacro></exportmacro> + <class>Browser</class> + <widget class="QWidget" name="Browser" > + <property name="geometry" > + <rect> + <x>0</x> + <y>0</y> + <width>765</width> + <height>515</height> + </rect> + </property> + <property name="windowTitle" > + <string>Qt SQL Browser</string> + </property> + <layout class="QVBoxLayout" > + <property name="margin" > + <number>8</number> + </property> + <property name="spacing" > + <number>6</number> + </property> + <item> + <widget class="QSplitter" name="splitter_2" > + <property name="sizePolicy" > + <sizepolicy> + <hsizetype>7</hsizetype> + <vsizetype>7</vsizetype> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="orientation" > + <enum>Qt::Horizontal</enum> + </property> + <widget class="ConnectionWidget" name="connectionWidget" > + <property name="sizePolicy" > + <sizepolicy> + <hsizetype>13</hsizetype> + <vsizetype>7</vsizetype> + <horstretch>1</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + </widget> + <widget class="QTableView" name="table" > + <property name="sizePolicy" > + <sizepolicy> + <hsizetype>7</hsizetype> + <vsizetype>7</vsizetype> + <horstretch>2</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="contextMenuPolicy" > + <enum>Qt::ActionsContextMenu</enum> + </property> + <property name="selectionBehavior" > + <enum>QAbstractItemView::SelectRows</enum> + </property> + </widget> + </widget> + </item> + <item> + <widget class="QGroupBox" name="groupBox" > + <property name="sizePolicy" > + <sizepolicy> + <hsizetype>5</hsizetype> + <vsizetype>3</vsizetype> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="maximumSize" > + <size> + <width>16777215</width> + <height>180</height> + </size> + </property> + <property name="title" > + <string>SQL Query</string> + </property> + <layout class="QVBoxLayout" > + <property name="margin" > + <number>9</number> + </property> + <property name="spacing" > + <number>6</number> + </property> + <item> + <widget class="QTextEdit" name="sqlEdit" > + <property name="sizePolicy" > + <sizepolicy> + <hsizetype>7</hsizetype> + <vsizetype>3</vsizetype> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="minimumSize" > + <size> + <width>0</width> + <height>18</height> + </size> + </property> + <property name="baseSize" > + <size> + <width>0</width> + <height>120</height> + </size> + </property> + </widget> + </item> + <item> + <layout class="QHBoxLayout" > + <property name="margin" > + <number>1</number> + </property> + <property name="spacing" > + <number>6</number> + </property> + <item> + <spacer> + <property name="orientation" > + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" > + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QPushButton" name="clearButton" > + <property name="text" > + <string>&Clear</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="submitButton" > + <property name="text" > + <string>&Submit</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + </item> + </layout> + <action name="insertRowAction" > + <property name="enabled" > + <bool>false</bool> + </property> + <property name="text" > + <string>&Insert Row</string> + </property> + <property name="statusTip" > + <string>Inserts a new Row</string> + </property> + </action> + <action name="deleteRowAction" > + <property name="enabled" > + <bool>false</bool> + </property> + <property name="text" > + <string>&Delete Row</string> + </property> + <property name="statusTip" > + <string>Deletes the current Row</string> + </property> + </action> + </widget> + <pixmapfunction></pixmapfunction> + <customwidgets> + <customwidget> + <class>ConnectionWidget</class> + <extends>QTreeView</extends> + <header>connectionwidget.h</header> + <container>0</container> + <pixmap></pixmap> + </customwidget> + </customwidgets> + <tabstops> + <tabstop>sqlEdit</tabstop> + <tabstop>clearButton</tabstop> + <tabstop>submitButton</tabstop> + <tabstop>connectionWidget</tabstop> + <tabstop>table</tabstop> + </tabstops> + <resources/> + <connections/> +</ui> diff --git a/examples/sql/sqlbrowser/connectionwidget.cpp b/examples/sql/sqlbrowser/connectionwidget.cpp new file mode 100644 index 0000000000..b68a20b309 --- /dev/null +++ b/examples/sql/sqlbrowser/connectionwidget.cpp @@ -0,0 +1,165 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "connectionwidget.h" + +#include <QtWidgets> +#include <QtSql> + +ConnectionWidget::ConnectionWidget(QWidget *parent) + : QWidget(parent) +{ + QVBoxLayout *layout = new QVBoxLayout(this); + tree = new QTreeWidget(this); + tree->setObjectName(QLatin1String("tree")); + tree->setHeaderLabels(QStringList(tr("database"))); + tree->header()->setResizeMode(QHeaderView::Stretch); + QAction *refreshAction = new QAction(tr("Refresh"), tree); + metaDataAction = new QAction(tr("Show Schema"), tree); + connect(refreshAction, SIGNAL(triggered()), SLOT(refresh())); + connect(metaDataAction, SIGNAL(triggered()), SLOT(showMetaData())); + tree->addAction(refreshAction); + tree->addAction(metaDataAction); + tree->setContextMenuPolicy(Qt::ActionsContextMenu); + + layout->addWidget(tree); + + QMetaObject::connectSlotsByName(this); +} + +ConnectionWidget::~ConnectionWidget() +{ +} + +static QString qDBCaption(const QSqlDatabase &db) +{ + QString nm = db.driverName(); + nm.append(QLatin1Char(':')); + if (!db.userName().isEmpty()) + nm.append(db.userName()).append(QLatin1Char('@')); + nm.append(db.databaseName()); + return nm; +} + +void ConnectionWidget::refresh() +{ + tree->clear(); + QStringList connectionNames = QSqlDatabase::connectionNames(); + + bool gotActiveDb = false; + for (int i = 0; i < connectionNames.count(); ++i) { + QTreeWidgetItem *root = new QTreeWidgetItem(tree); + QSqlDatabase db = QSqlDatabase::database(connectionNames.at(i), false); + root->setText(0, qDBCaption(db)); + if (connectionNames.at(i) == activeDb) { + gotActiveDb = true; + setActive(root); + } + if (db.isOpen()) { + QStringList tables = db.tables(); + for (int t = 0; t < tables.count(); ++t) { + QTreeWidgetItem *table = new QTreeWidgetItem(root); + table->setText(0, tables.at(t)); + } + } + } + if (!gotActiveDb) { + activeDb = connectionNames.value(0); + setActive(tree->topLevelItem(0)); + } + + tree->doItemsLayout(); // HACK +} + +QSqlDatabase ConnectionWidget::currentDatabase() const +{ + return QSqlDatabase::database(activeDb); +} + +static void qSetBold(QTreeWidgetItem *item, bool bold) +{ + QFont font = item->font(0); + font.setBold(bold); + item->setFont(0, font); +} + +void ConnectionWidget::setActive(QTreeWidgetItem *item) +{ + for (int i = 0; i < tree->topLevelItemCount(); ++i) { + if (tree->topLevelItem(i)->font(0).bold()) + qSetBold(tree->topLevelItem(i), false); + } + + if (!item) + return; + + qSetBold(item, true); + activeDb = QSqlDatabase::connectionNames().value(tree->indexOfTopLevelItem(item)); +} + +void ConnectionWidget::on_tree_itemActivated(QTreeWidgetItem *item, int /* column */) +{ + + if (!item) + return; + + if (!item->parent()) { + setActive(item); + } else { + setActive(item->parent()); + emit tableActivated(item->text(0)); + } +} + +void ConnectionWidget::showMetaData() +{ + QTreeWidgetItem *cItem = tree->currentItem(); + if (!cItem || !cItem->parent()) + return; + setActive(cItem->parent()); + emit metaDataRequested(cItem->text(0)); +} + +void ConnectionWidget::on_tree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *) +{ + metaDataAction->setEnabled(current && current->parent()); +} + diff --git a/examples/sql/sqlbrowser/connectionwidget.h b/examples/sql/sqlbrowser/connectionwidget.h new file mode 100644 index 0000000000..aa04fc25bf --- /dev/null +++ b/examples/sql/sqlbrowser/connectionwidget.h @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef CONNECTIONWIDGET_H +#define CONNECTIONWIDGET_H + +#include <QWidget> + +QT_FORWARD_DECLARE_CLASS(QTreeWidget) +QT_FORWARD_DECLARE_CLASS(QTreeWidgetItem) +QT_FORWARD_DECLARE_CLASS(QSqlDatabase) +QT_FORWARD_DECLARE_CLASS(QMenu) + +class ConnectionWidget: public QWidget +{ + Q_OBJECT +public: + ConnectionWidget(QWidget *parent = 0); + virtual ~ConnectionWidget(); + + QSqlDatabase currentDatabase() const; + +signals: + void tableActivated(const QString &table); + void metaDataRequested(const QString &tableName); + +public slots: + void refresh(); + void showMetaData(); + void on_tree_itemActivated(QTreeWidgetItem *item, int column); + void on_tree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); + +private: + void setActive(QTreeWidgetItem *); + + QTreeWidget *tree; + QAction *metaDataAction; + QString activeDb; +}; + +#endif diff --git a/examples/sql/sqlbrowser/main.cpp b/examples/sql/sqlbrowser/main.cpp new file mode 100644 index 0000000000..6e0b129445 --- /dev/null +++ b/examples/sql/sqlbrowser/main.cpp @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "browser.h" + +#include <QtCore> +#include <QtWidgets> +#include <QtSql> + +void addConnectionsFromCommandline(const QStringList &args, Browser *browser) +{ + for (int i = 1; i < args.count(); ++i) { + QUrl url(args.at(i), QUrl::TolerantMode); + if (!url.isValid()) { + qWarning("Invalid URL: %s", qPrintable(args.at(i))); + continue; + } + QSqlError err = browser->addConnection(url.scheme(), url.path().mid(1), url.host(), + url.userName(), url.password(), url.port(-1)); + if (err.type() != QSqlError::NoError) + qDebug() << "Unable to open connection:" << err; + } +} + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QMainWindow mainWin; + mainWin.setWindowTitle(QObject::tr("Qt SQL Browser")); + + Browser browser(&mainWin); + mainWin.setCentralWidget(&browser); + + QMenu *fileMenu = mainWin.menuBar()->addMenu(QObject::tr("&File")); + fileMenu->addAction(QObject::tr("Add &Connection..."), &browser, SLOT(addConnection())); + fileMenu->addSeparator(); + fileMenu->addAction(QObject::tr("&Quit"), &app, SLOT(quit())); + + QMenu *helpMenu = mainWin.menuBar()->addMenu(QObject::tr("&Help")); + helpMenu->addAction(QObject::tr("About"), &browser, SLOT(about())); + helpMenu->addAction(QObject::tr("About Qt"), qApp, SLOT(aboutQt())); + + QObject::connect(&browser, SIGNAL(statusMessage(QString)), + mainWin.statusBar(), SLOT(showMessage(QString))); + + addConnectionsFromCommandline(app.arguments(), &browser); + mainWin.show(); + if (QSqlDatabase::connectionNames().isEmpty()) + QMetaObject::invokeMethod(&browser, "addConnection", Qt::QueuedConnection); + + return app.exec(); +} diff --git a/examples/sql/sqlbrowser/qsqlconnectiondialog.cpp b/examples/sql/sqlbrowser/qsqlconnectiondialog.cpp new file mode 100644 index 0000000000..56b6c031db --- /dev/null +++ b/examples/sql/sqlbrowser/qsqlconnectiondialog.cpp @@ -0,0 +1,115 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qsqlconnectiondialog.h" +#include "ui_qsqlconnectiondialog.h" + +#include <QSqlDatabase> + +QSqlConnectionDialog::QSqlConnectionDialog(QWidget *parent) + : QDialog(parent) +{ + ui.setupUi(this); + + QStringList drivers = QSqlDatabase::drivers(); + + // remove compat names + drivers.removeAll("QMYSQL3"); + drivers.removeAll("QOCI8"); + drivers.removeAll("QODBC3"); + drivers.removeAll("QPSQL7"); + drivers.removeAll("QTDS7"); + + if (!drivers.contains("QSQLITE")) + ui.dbCheckBox->setEnabled(false); + + ui.comboDriver->addItems(drivers); +} + +QSqlConnectionDialog::~QSqlConnectionDialog() +{ +} + +QString QSqlConnectionDialog::driverName() const +{ + return ui.comboDriver->currentText(); +} + +QString QSqlConnectionDialog::databaseName() const +{ + return ui.editDatabase->text(); +} + +QString QSqlConnectionDialog::userName() const +{ + return ui.editUsername->text(); +} + +QString QSqlConnectionDialog::password() const +{ + return ui.editPassword->text(); +} + +QString QSqlConnectionDialog::hostName() const +{ + return ui.editHostname->text(); +} + +int QSqlConnectionDialog::port() const +{ + return ui.portSpinBox->value(); +} + +bool QSqlConnectionDialog::useInMemoryDatabase() const +{ + return ui.dbCheckBox->isChecked(); +} + +void QSqlConnectionDialog::on_okButton_clicked() +{ + if (ui.comboDriver->currentText().isEmpty()) { + QMessageBox::information(this, tr("No database driver selected"), + tr("Please select a database driver")); + ui.comboDriver->setFocus(); + } else { + accept(); + } +} diff --git a/examples/sql/sqlbrowser/qsqlconnectiondialog.h b/examples/sql/sqlbrowser/qsqlconnectiondialog.h new file mode 100644 index 0000000000..8c4519a195 --- /dev/null +++ b/examples/sql/sqlbrowser/qsqlconnectiondialog.h @@ -0,0 +1,74 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the demonstration applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSQLCONNECTIONDIALOG_H +#define QSQLCONNECTIONDIALOG_H + +#include <QDialog> +#include <QMessageBox> + +#include "ui_qsqlconnectiondialog.h" + +class QSqlConnectionDialog: public QDialog +{ + Q_OBJECT +public: + QSqlConnectionDialog(QWidget *parent = 0); + ~QSqlConnectionDialog(); + + QString driverName() const; + QString databaseName() const; + QString userName() const; + QString password() const; + QString hostName() const; + int port() const; + bool useInMemoryDatabase() const; + +private slots: + void on_okButton_clicked(); + void on_cancelButton_clicked() { reject(); } + void on_dbCheckBox_clicked() { ui.connGroupBox->setEnabled(!ui.dbCheckBox->isChecked()); } + +private: + Ui::QSqlConnectionDialogUi ui; +}; + +#endif diff --git a/examples/sql/sqlbrowser/qsqlconnectiondialog.ui b/examples/sql/sqlbrowser/qsqlconnectiondialog.ui new file mode 100644 index 0000000000..91a8700579 --- /dev/null +++ b/examples/sql/sqlbrowser/qsqlconnectiondialog.ui @@ -0,0 +1,224 @@ +<ui version="4.0" > + <author></author> + <comment></comment> + <exportmacro></exportmacro> + <class>QSqlConnectionDialogUi</class> + <widget class="QDialog" name="QSqlConnectionDialogUi" > + <property name="geometry" > + <rect> + <x>0</x> + <y>0</y> + <width>315</width> + <height>302</height> + </rect> + </property> + <property name="windowTitle" > + <string>Connect...</string> + </property> + <layout class="QVBoxLayout" > + <property name="margin" > + <number>8</number> + </property> + <property name="spacing" > + <number>6</number> + </property> + <item> + <widget class="QGroupBox" name="connGroupBox" > + <property name="title" > + <string>Connection settings</string> + </property> + <layout class="QGridLayout" > + <property name="margin" > + <number>8</number> + </property> + <property name="spacing" > + <number>6</number> + </property> + <item row="0" column="1" > + <widget class="QComboBox" name="comboDriver" /> + </item> + <item row="2" column="0" > + <widget class="QLabel" name="textLabel4" > + <property name="text" > + <string>&Username:</string> + </property> + <property name="buddy" > + <cstring>editUsername</cstring> + </property> + </widget> + </item> + <item row="0" column="0" > + <widget class="QLabel" name="textLabel2" > + <property name="text" > + <string>D&river</string> + </property> + <property name="buddy" > + <cstring>comboDriver</cstring> + </property> + </widget> + </item> + <item row="1" column="1" > + <widget class="QLineEdit" name="editDatabase" /> + </item> + <item row="5" column="1" > + <widget class="QSpinBox" name="portSpinBox" > + <property name="specialValueText" > + <string>Default</string> + </property> + <property name="maximum" > + <number>65535</number> + </property> + <property name="minimum" > + <number>-1</number> + </property> + <property name="value" > + <number>-1</number> + </property> + </widget> + </item> + <item row="1" column="0" > + <widget class="QLabel" name="textLabel3" > + <property name="text" > + <string>Database Name:</string> + </property> + <property name="buddy" > + <cstring>editDatabase</cstring> + </property> + </widget> + </item> + <item row="3" column="1" > + <widget class="QLineEdit" name="editPassword" > + <property name="echoMode" > + <enum>QLineEdit::Password</enum> + </property> + </widget> + </item> + <item row="2" column="1" > + <widget class="QLineEdit" name="editUsername" /> + </item> + <item row="4" column="1" > + <widget class="QLineEdit" name="editHostname" /> + </item> + <item row="4" column="0" > + <widget class="QLabel" name="textLabel5" > + <property name="text" > + <string>&Hostname:</string> + </property> + <property name="buddy" > + <cstring>editHostname</cstring> + </property> + </widget> + </item> + <item row="5" column="0" > + <widget class="QLabel" name="textLabel5_2" > + <property name="text" > + <string>P&ort:</string> + </property> + <property name="buddy" > + <cstring>portSpinBox</cstring> + </property> + </widget> + </item> + <item row="3" column="0" > + <widget class="QLabel" name="textLabel4_2" > + <property name="text" > + <string>&Password:</string> + </property> + <property name="buddy" > + <cstring>editPassword</cstring> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item> + <layout class="QHBoxLayout" > + <property name="margin" > + <number>0</number> + </property> + <property name="spacing" > + <number>6</number> + </property> + <item> + <spacer> + <property name="orientation" > + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" > + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QCheckBox" name="dbCheckBox" > + <property name="text" > + <string>Us&e predefined in-memory database</string> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" > + <property name="margin" > + <number>0</number> + </property> + <property name="spacing" > + <number>6</number> + </property> + <item> + <spacer> + <property name="orientation" > + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeType" > + <enum>QSizePolicy::Expanding</enum> + </property> + <property name="sizeHint" > + <size> + <width>20</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QPushButton" name="okButton" > + <property name="text" > + <string>&OK</string> + </property> + <property name="default" > + <bool>true</bool> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="cancelButton" > + <property name="text" > + <string>&Cancel</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + <pixmapfunction></pixmapfunction> + <tabstops> + <tabstop>comboDriver</tabstop> + <tabstop>editDatabase</tabstop> + <tabstop>editUsername</tabstop> + <tabstop>editPassword</tabstop> + <tabstop>editHostname</tabstop> + <tabstop>portSpinBox</tabstop> + <tabstop>dbCheckBox</tabstop> + <tabstop>okButton</tabstop> + <tabstop>cancelButton</tabstop> + </tabstops> + <resources/> + <connections/> +</ui> diff --git a/examples/sql/sqlbrowser/sqlbrowser.pro b/examples/sql/sqlbrowser/sqlbrowser.pro new file mode 100644 index 0000000000..73a17b28e7 --- /dev/null +++ b/examples/sql/sqlbrowser/sqlbrowser.pro @@ -0,0 +1,25 @@ +TEMPLATE = app +TARGET = sqlbrowser + +QT += sql widgets + +HEADERS = browser.h connectionwidget.h qsqlconnectiondialog.h +SOURCES = main.cpp browser.cpp connectionwidget.cpp qsqlconnectiondialog.cpp + +FORMS = browserwidget.ui qsqlconnectiondialog.ui +build_all:!build_pass { + CONFIG -= build_all + CONFIG += release +} + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/qtbase/sql/sqlbrowser +sources.files = $$SOURCES $$HEADERS $$FORMS *.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/qtbase/sql/sqlbrowser +INSTALLS += target sources + +symbian: CONFIG += qt_example + +wince*: { + DEPLOYMENT_PLUGIN += qsqlite +} |