diff options
Diffstat (limited to 'examples/quickcontrols2/chattutorial/chapter4-models')
10 files changed, 753 insertions, 0 deletions
diff --git a/examples/quickcontrols2/chattutorial/chapter4-models/ContactPage.qml b/examples/quickcontrols2/chattutorial/chapter4-models/ContactPage.qml new file mode 100644 index 00000000..a6491495 --- /dev/null +++ b/examples/quickcontrols2/chattutorial/chapter4-models/ContactPage.qml @@ -0,0 +1,80 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.6 +import QtQuick.Controls 2.0 + +import io.qt.examples.chattutorial 1.0 + +Page { + id: root + + header: ToolBar { + Label { + text: qsTr("Contacts") + font.pixelSize: 20 + anchors.centerIn: parent + } + } + + ListView { + id: listView + anchors.fill: parent + topMargin: 48 + leftMargin: 48 + bottomMargin: 48 + rightMargin: 48 + spacing: 20 + model: SqlContactModel {} + delegate: ItemDelegate { + text: model.display + width: listView.width - listView.leftMargin - listView.rightMargin + height: avatar.implicitHeight + leftPadding: avatar.implicitWidth + 32 + onClicked: root.StackView.view.push("qrc:/ConversationPage.qml", { inConversationWith: model.display }) + + Image { + id: avatar + source: "qrc:/" + model.display + ".png" + } + } + } +} + diff --git a/examples/quickcontrols2/chattutorial/chapter4-models/ConversationPage.qml b/examples/quickcontrols2/chattutorial/chapter4-models/ConversationPage.qml new file mode 100644 index 00000000..5c91a206 --- /dev/null +++ b/examples/quickcontrols2/chattutorial/chapter4-models/ConversationPage.qml @@ -0,0 +1,155 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.6 +import QtQuick.Layouts 1.3 +import QtQuick.Controls 2.0 + +import io.qt.examples.chattutorial 1.0 + +Page { + id: root + + property string inConversationWith + + header: ToolBar { + ToolButton { + text: qsTr("Back") + anchors.left: parent.left + anchors.leftMargin: 10 + anchors.verticalCenter: parent.verticalCenter + onClicked: root.StackView.view.pop() + } + + Label { + id: pageTitle + text: inConversationWith + font.pixelSize: 20 + anchors.centerIn: parent + } + } + + ColumnLayout { + anchors.fill: parent + + ListView { + id: listView + Layout.fillWidth: true + Layout.fillHeight: true + Layout.margins: pane.leftPadding + messageField.leftPadding + displayMarginBeginning: 40 + displayMarginEnd: 40 + verticalLayoutDirection: ListView.BottomToTop + spacing: 12 + model: SqlConversationModel { + recipient: inConversationWith + } + delegate: Column { + anchors.right: sentByMe ? parent.right : undefined + spacing: 6 + + readonly property bool sentByMe: model.recipient !== "Me" + + Row { + id: messageRow + spacing: 6 + anchors.right: sentByMe ? parent.right : undefined + + Image { + id: avatar + source: !sentByMe ? "qrc:/" + model.author + ".png" : "" + } + + Rectangle { + width: Math.min(messageText.implicitWidth + 24, + listView.width - (!sentByMe ? avatar.width + messageRow.spacing : 0)) + height: messageText.implicitHeight + 24 + color: sentByMe ? "lightgrey" : "steelblue" + + Label { + id: messageText + text: model.message + color: sentByMe ? "black" : "white" + anchors.fill: parent + anchors.margins: 12 + wrapMode: Label.Wrap + } + } + } + + Label { + id: timestampText + text: Qt.formatDateTime(model.timestamp, "d MMM hh:mm") + color: "lightgrey" + anchors.right: sentByMe ? parent.right : undefined + } + } + + ScrollBar.vertical: ScrollBar {} + } + + Pane { + id: pane + Layout.fillWidth: true + + RowLayout { + width: parent.width + + TextArea { + id: messageField + Layout.fillWidth: true + placeholderText: qsTr("Compose message") + wrapMode: TextArea.Wrap + } + + Button { + id: sendButton + text: qsTr("Send") + enabled: messageField.length > 0 + onClicked: { + listView.model.sendMessage(inConversationWith, messageField.text); + messageField.text = ""; + } + } + } + } + } +} + diff --git a/examples/quickcontrols2/chattutorial/chapter4-models/chapter4-models.pro b/examples/quickcontrols2/chattutorial/chapter4-models/chapter4-models.pro new file mode 100644 index 00000000..d62eacc0 --- /dev/null +++ b/examples/quickcontrols2/chattutorial/chapter4-models/chapter4-models.pro @@ -0,0 +1,20 @@ +TEMPLATE = app + +QT += qml quick sql +CONFIG += c++11 + +!contains(sql-drivers, sqlite): QTPLUGIN += qsqlite + +HEADERS += sqlcontactmodel.h \ + sqlconversationmodel.h + +SOURCES += main.cpp \ + sqlcontactmodel.cpp \ + sqlconversationmodel.cpp + +RESOURCES += \ + qml.qrc \ + ../shared/shared.qrc + +target.path = $$[QT_INSTALL_EXAMPLES]/quickcontrols2/chattutorial/chapter4-models +INSTALLS += target diff --git a/examples/quickcontrols2/chattutorial/chapter4-models/main.cpp b/examples/quickcontrols2/chattutorial/chapter4-models/main.cpp new file mode 100644 index 00000000..9f2109fa --- /dev/null +++ b/examples/quickcontrols2/chattutorial/chapter4-models/main.cpp @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QGuiApplication> +#include <QStandardPaths> +#include <QSqlDatabase> +#include <QSqlError> +#include <QtQml> + +#include "sqlcontactmodel.h" +#include "sqlconversationmodel.h" + +static void connectToDatabase() +{ + QSqlDatabase database = QSqlDatabase::database(); + if (!database.isValid()) { + database = QSqlDatabase::addDatabase("QSQLITE"); + if (!database.isValid()) + qFatal("Cannot add database: %s", qPrintable(database.lastError().text())); + } + + const QDir writeDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); + if (!writeDir.mkpath(".")) + qFatal("Failed to create writable directory at %s", qPrintable(writeDir.absolutePath())); + + // Ensure that we have a writable location on all devices. + const QString fileName = writeDir.absolutePath() + "/chat-database.sqlite3"; + // When using the SQLite driver, open() will create the SQLite database if it doesn't exist. + database.setDatabaseName(fileName); + if (!database.open()) { + qFatal("Cannot open database: %s", qPrintable(database.lastError().text())); + QFile::remove(fileName); + } +} + +int main(int argc, char *argv[]) +{ + QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + QGuiApplication app(argc, argv); + + qmlRegisterType<SqlContactModel>("io.qt.examples.chattutorial", 1, 0, "SqlContactModel"); + qmlRegisterType<SqlConversationModel>("io.qt.examples.chattutorial", 1, 0, "SqlConversationModel"); + + connectToDatabase(); + + QQmlApplicationEngine engine; + engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); + if (engine.rootObjects().isEmpty()) + return -1; + + return app.exec(); +} + diff --git a/examples/quickcontrols2/chattutorial/chapter4-models/main.qml b/examples/quickcontrols2/chattutorial/chapter4-models/main.qml new file mode 100644 index 00000000..5bc9e95d --- /dev/null +++ b/examples/quickcontrols2/chattutorial/chapter4-models/main.qml @@ -0,0 +1,56 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +import QtQuick 2.6 +import QtQuick.Controls 2.0 + +ApplicationWindow { + id: window + width: 540 + height: 960 + visible: true + + StackView { + id: stackView + anchors.fill: parent + initialItem: ContactPage {} + } +} + diff --git a/examples/quickcontrols2/chattutorial/chapter4-models/qml.qrc b/examples/quickcontrols2/chattutorial/chapter4-models/qml.qrc new file mode 100644 index 00000000..a72e1b71 --- /dev/null +++ b/examples/quickcontrols2/chattutorial/chapter4-models/qml.qrc @@ -0,0 +1,7 @@ +<RCC> + <qresource prefix="/"> + <file>main.qml</file> + <file>ContactPage.qml</file> + <file>ConversationPage.qml</file> + </qresource> +</RCC> diff --git a/examples/quickcontrols2/chattutorial/chapter4-models/sqlcontactmodel.cpp b/examples/quickcontrols2/chattutorial/chapter4-models/sqlcontactmodel.cpp new file mode 100644 index 00000000..d1cfb796 --- /dev/null +++ b/examples/quickcontrols2/chattutorial/chapter4-models/sqlcontactmodel.cpp @@ -0,0 +1,80 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "sqlcontactmodel.h" + +#include <QDebug> +#include <QSqlError> +#include <QSqlQuery> + +static void createTable() +{ + if (QSqlDatabase::database().tables().contains(QStringLiteral("Contacts"))) { + // The table already exists; we don't need to do anything. + return; + } + + QSqlQuery query; + if (!query.exec( + "CREATE TABLE IF NOT EXISTS 'Contacts' (" + " 'name' TEXT NOT NULL," + " PRIMARY KEY(name)" + ")")) { + qFatal("Failed to query database: %s", qPrintable(query.lastError().text())); + } + + query.exec("INSERT INTO Contacts VALUES('Albert Einstein')"); + query.exec("INSERT INTO Contacts VALUES('Ernest Hemingway')"); + query.exec("INSERT INTO Contacts VALUES('Hans Gude')"); +} + +SqlContactModel::SqlContactModel(QObject *parent) : + QSqlQueryModel(parent) +{ + createTable(); + + QSqlQuery query; + if (!query.exec("SELECT * FROM Contacts")) + qFatal("Contacts SELECT query failed: %s", qPrintable(query.lastError().text())); + + setQuery(query); + if (lastError().isValid()) + qFatal("Cannot set query on SqlContactModel: %s", qPrintable(lastError().text())); +} diff --git a/examples/quickcontrols2/chattutorial/chapter4-models/sqlcontactmodel.h b/examples/quickcontrols2/chattutorial/chapter4-models/sqlcontactmodel.h new file mode 100644 index 00000000..00dd6a6f --- /dev/null +++ b/examples/quickcontrols2/chattutorial/chapter4-models/sqlcontactmodel.h @@ -0,0 +1,52 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SQLCONTACTMODEL_H +#define SQLCONTACTMODEL_H + +#include <QSqlQueryModel> + +class SqlContactModel : public QSqlQueryModel +{ +public: + SqlContactModel(QObject *parent = 0); +}; + +#endif // SQLCONTACTMODEL_H diff --git a/examples/quickcontrols2/chattutorial/chapter4-models/sqlconversationmodel.cpp b/examples/quickcontrols2/chattutorial/chapter4-models/sqlconversationmodel.cpp new file mode 100644 index 00000000..56f1b838 --- /dev/null +++ b/examples/quickcontrols2/chattutorial/chapter4-models/sqlconversationmodel.cpp @@ -0,0 +1,144 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "sqlconversationmodel.h" + +#include <QDateTime> +#include <QDebug> +#include <QSqlError> +#include <QSqlRecord> +#include <QSqlQuery> + +static const char *conversationsTableName = "Conversations"; + +static void createTable() +{ + if (QSqlDatabase::database().tables().contains(conversationsTableName)) { + // The table already exists; we don't need to do anything. + return; + } + + QSqlQuery query; + if (!query.exec( + "CREATE TABLE IF NOT EXISTS 'Conversations' (" + "'author' TEXT NOT NULL," + "'recipient' TEXT NOT NULL," + "'timestamp' TEXT NOT NULL," + "'message' TEXT NOT NULL," + "FOREIGN KEY('author') REFERENCES Contacts ( name )," + "FOREIGN KEY('recipient') REFERENCES Contacts ( name )" + ")")) { + qFatal("Failed to query database: %s", qPrintable(query.lastError().text())); + } + + query.exec("INSERT INTO Conversations VALUES('Me', 'Ernest Hemingway', '2016-01-07T14:36:06', 'Hello!')"); + query.exec("INSERT INTO Conversations VALUES('Ernest Hemingway', 'Me', '2016-01-07T14:36:16', 'Good afternoon.')"); + query.exec("INSERT INTO Conversations VALUES('Me', 'Albert Einstein', '2016-01-01T11:24:53', 'Hi!')"); + query.exec("INSERT INTO Conversations VALUES('Albert Einstein', 'Me', '2016-01-07T14:36:16', 'Good morning.')"); + query.exec("INSERT INTO Conversations VALUES('Hans Gude', 'Me', '2015-11-20T06:30:02', 'God morgen. Har du fått mitt maleri?')"); + query.exec("INSERT INTO Conversations VALUES('Me', 'Hans Gude', '2015-11-20T08:21:03', 'God morgen, Hans. Ja, det er veldig fint. Tusen takk! " + "Hvor mange timer har du brukt på den?')"); +} + +SqlConversationModel::SqlConversationModel(QObject *parent) : + QSqlTableModel(parent) +{ + createTable(); + setTable(conversationsTableName); + setSort(2, Qt::DescendingOrder); + // Ensures that the model is sorted correctly after submitting a new row. + setEditStrategy(QSqlTableModel::OnManualSubmit); +} + +QString SqlConversationModel::recipient() const +{ + return m_recipient; +} + +void SqlConversationModel::setRecipient(const QString &recipient) +{ + if (recipient == m_recipient) + return; + + m_recipient = recipient; + + const QString filterString = QString::fromLatin1( + "(recipient = '%1' AND author = 'Me') OR (recipient = 'Me' AND author='%1')").arg(m_recipient); + setFilter(filterString); + select(); + + emit recipientChanged(); +} + +QVariant SqlConversationModel::data(const QModelIndex &index, int role) const +{ + if (role < Qt::UserRole) + return QSqlTableModel::data(index, role); + + const QSqlRecord sqlRecord = record(index.row()); + return sqlRecord.value(role - Qt::UserRole); +} + +QHash<int, QByteArray> SqlConversationModel::roleNames() const +{ + QHash<int, QByteArray> names; + names[Qt::UserRole] = "author"; + names[Qt::UserRole + 1] = "recipient"; + names[Qt::UserRole + 2] = "timestamp"; + names[Qt::UserRole + 3] = "message"; + return names; +} + +void SqlConversationModel::sendMessage(const QString &recipient, const QString &message) +{ + const QString timestamp = QDateTime::currentDateTime().toString(Qt::ISODate); + + QSqlRecord newRecord = record(); + newRecord.setValue("author", "Me"); + newRecord.setValue("recipient", recipient); + newRecord.setValue("timestamp", timestamp); + newRecord.setValue("message", message); + if (!insertRecord(rowCount(), newRecord)) { + qWarning() << "Failed to send message:" << lastError().text(); + return; + } + + submitAll(); +} diff --git a/examples/quickcontrols2/chattutorial/chapter4-models/sqlconversationmodel.h b/examples/quickcontrols2/chattutorial/chapter4-models/sqlconversationmodel.h new file mode 100644 index 00000000..0ce12049 --- /dev/null +++ b/examples/quickcontrols2/chattutorial/chapter4-models/sqlconversationmodel.h @@ -0,0 +1,69 @@ +/**************************************************************************** +** +** Copyright (C) 2015 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SQLCONVERSATIONMODEL_H +#define SQLCONVERSATIONMODEL_H + +#include <QSqlTableModel> + +class SqlConversationModel : public QSqlTableModel +{ + Q_OBJECT + Q_PROPERTY(QString recipient READ recipient WRITE setRecipient NOTIFY recipientChanged) + +public: + SqlConversationModel(QObject *parent = 0); + + QString recipient() const; + void setRecipient(const QString &recipient); + + QVariant data(const QModelIndex &index, int role) const Q_DECL_OVERRIDE; + QHash<int, QByteArray> roleNames() const Q_DECL_OVERRIDE; + + Q_INVOKABLE void sendMessage(const QString &recipient, const QString &message); + +signals: + void recipientChanged(); + +private: + QString m_recipient; +}; + +#endif // SQLCONVERSATIONMODEL_H |