Manual de qml + sqlite

306 views
Skip to first unread message

Johan Vallejo

unread,
Oct 15, 2013, 7:46:48 PM10/15/13
to qt-es...@googlegroups.com

Estimados,  alguna alma caritativa que pueda pasarme un link de referencia para iniciarme con sqlite + qml.... estuve buscando en san google pero no encuentro mucha información, gracias.

Saludos,
Johan

Juancar

unread,
Oct 16, 2013, 7:56:57 AM10/16/13
to qt-es...@googlegroups.com
Es bastante sencillo, la documentación sobre javascript y el manejo de bases de datos la puedes encontrar en http://qt-project.org/doc/qt-5.0/qtquick/qmlmodule-qtquick-localstorage2-qtquick-localstorage-2.html

Te pego un ejemplo de uso:

function openDB() {
  print("noteDB.createDB()")
  _db = openDatabaseSync("StickyNotesDB","1.0",
  "The stickynotes Database", 1000000);
}

function createNoteTable() {
  print("noteDB.createTable()")
  _db.transaction( function(tx) {
  tx.executeSql(
    "CREATE TABLE IF NOT EXISTS note
    (noteId INTEGER PRIMARY KEY AUTOINCREMENT,
    x INTEGER,
    y INTEGER,
    noteText TEXT,
    markerId TEXT)")
  })
}

function readNotesFromPage(markerId) {
  print("noteDB.readNotesFromPage() " + markerId)
  var noteItems = {}
  _db.readTransaction( function(tx) {
    var rs = tx.executeSql(
      "SELECT
      FROM note WHERE markerId=?
      ORDER BY markerid DESC", [markerId] );
    var item
    for (var i=0; i< rs.rows.length; i++) {
      item = rs.rows.item(i)
      noteItems[item.noteId] = item;
    }
  })
}
return noteItems

Juancar

unread,
Oct 16, 2013, 7:59:54 AM10/16/13
to qt-es...@googlegroups.com
Un trozo de código para insertar datos en la misma DB

function saveNotes(noteItems, markerId) {
  for (var i=0; i<noteItems.length; ++i) {
    var noteItem = noteItems[i]
    _db.transaction( function(tx) {
      tx.executeSql(
        "INSERT INTO note (markerId, x, y, noteText)
        VALUES(?,?,?,?)",
        [markerId, noteItem.x, noteItem.y, noteItem.noteText]);
    })

  }
}


El miércoles, 16 de octubre de 2013 01:46:48 UTC+2, Johan Vallejo escribió:

Johan Vallejo

unread,
Oct 16, 2013, 12:57:18 PM10/16/13
to qt-es...@googlegroups.com
Juanca, gracias por responder.
Si pude ver algunos ejemplos sobre openDatabaseSync(), pero lo que no me queda claro es como le digo a la función que la BD de sqlite esta en otra ruta, por ejemplo si la BD la tengo en C:\BD\logistica.db

function openDB() {
  print("noteDB.createDB()")
  _db = openDatabaseSync("StickyNotesDB","1.0","The stickynotes Database", 1000000);
}



Por otro lado, es recomendable interactuar con la BD desde qml usando openDatabaseSync()  o seria mas optimo manejarlo desde un cpp como el siguiente ejemplo:

main.cpp
=======================================================================
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QtQuick2ApplicationViewer viewer;

     viewer.rootContext()->setContextProperty("QtQuick2ApplicationViewer", &viewer);
 
           QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
      db.setDatabaseName("d:\sqlite\mibase.db");

      if(!db.open())
      {
          //qDebug() << db.lastError();
          qFatal("No conectado!");
      }

      else

         qDebug("Conectado.");
      

      QSqlQueryModel *someSqlModel = new QSqlQueryModel();
      someSqlModel->setQuery("select nombre from alumno");

      QQmlContext *context = viewer.rootContext();
      context->setContextProperty("datamodel", someSqlModel);
 
      viewer.setMainQmlFile(QStringLiteral("qml/prueba2/main.qml"));
      viewer.showFullScreen();
      viewer.showExpanded();
      viewer.show();

      return app.exec();
}



main.qml
=====================================
Rectangle {
    id: window
    width: 600
    height: 468

    ListView {
        width: 200; height: 200
        model: datamodel
        delegate: Row {
            Rectangle {
                width: 100; height: 40
                Text {
                    anchors.fill: parent
                    text: display
                }
            }
        }
    }
}


Mi problema en este caso, es que los datos consultados por QSqlQueryModel y QQmlContext
no llegan a ser visibles en el main.qml


Gracias.


Saludos,
Johan


--
Has recibido este mensaje porque estás suscrito al grupo "Qt-español" de Grupos de Google.
Para anular la suscripción a este grupo y dejar de recibir sus correos electrónicos, envía un correo electrónico a qt-espanol+...@googlegroups.com.
Para publicar una entrada en este grupo, envía un correo electrónico a qt-es...@googlegroups.com.
Visita este grupo en http://groups.google.com/group/qt-espanol.
Para obtener más opciones, visita https://groups.google.com/groups/opt_out.

Juancar

unread,
Oct 16, 2013, 3:34:52 PM10/16/13
to qt-es...@googlegroups.com

Lo primero que debes comprobar en C++ es que te devuelve la consulta que estás haciendo a la base de datos, es posible que no estés recibiendo los datos y por lo tanto no los puede mostrar.

Para decirle a QML la ruta de la base de datos encuentras la respuesta en http://qt-project.org/doc/qt-5.0/qtquick/qmlmodule-qtquick-localstorage2-qtquick-localstorage-2.html donde dice claramente:

These databases are user-specific and QML-specific, but accessible to all QML applications. They are stored in the Databases subdirectory of QQmlEngine::offlineStoragePath(), currently as SQLite databases.

Database connections are automatically closed during Javascript garbage collection.

Ten en cuenta que solo tienes que pasar el nombre de la base de datos, no el nombre del fichero.

Para pasarle el path usa la siguiente línea
viewer.engine()->setOfflineStoragePath("Path");

O le añades lo siguiente al constructor o una función adHoc de viewer:
engine()->setOfflineStoragePath("Path");

En principio es mejor no andar mezclando C++ y QML si no es necesario crear extensiones o utilidades para tu aplicación.

Mira la documentación de qt-project.org/doc/qt-5.0/qtqml/qqmlengine.htm y http://qt-project.org/doc/qt-5.0/qtquick/qquickview.html

Johan Vallejo

unread,
Nov 25, 2013, 10:49:34 AM11/25/13
to qt-es...@googlegroups.com
Estimado juncar, estuve haciendo algunas pruebas referente al mismo tema y a los enlaces que enviaste pero sigo con algunos problemas espero te sea algo familiar.

Seguí las indicaciones del ejemplo que esta en el siguiente enlace: 

A mi parecer no es un ejemplo 100% funcional por lo que estuve googleando y encontré esto: 

Incluso, hice los cambios sugeridos en el post de StackOverFlow pero nada.

También, trate de agregar/cambiar la librería  #include <QQmlComponent> ó #include <QtQml/QQmlContext>
pero el mensaje de error es el mismo .
La ruta de mi archivo mail.qml es correcta: qml/untitled3/main.qml

Este es el mensaje de error: 

error: variable 'QQmlComponent component' has initializer but incomplete type
     QQmlComponent component(&engine, QUrl::fromLocalFile("qml/untitled3/main.qml"));
                            ^

Este es el contenido de mis archivos, alguna idea???


untitled3.pro

# Add more folders to ship with the application, here
folder_01.source = qml/untitled3
folder_01.target = qml
DEPLOYMENTFOLDERS = folder_01

# Additional import path used to resolve QML modules in Creator's code model
QML_IMPORT_PATH =

# If your application uses the Qt Mobility libraries, uncomment the following
# lines and add the respective components to the MOBILITY variable.
# CONFIG += mobility
# MOBILITY +=

# The .cpp file which was generated for your project. Feel free to hack it.
SOURCES += main.cpp

# Installation path
# target.path =

# Please do not modify the following two lines. Required for deployment.
include(qtquick2applicationviewer/qtquick2applicationviewer.pri)
qtcAddDeployment()

HEADERS += \
    message.h

message.h

#ifndef MESSAGE_H
#define MESSAGE_H
#include <QObject>
class Message : public QObject
{
Q_OBJECT
Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged)
public:
    void setAuthor(const QString &a) {
        if (a != m_author) {
            m_author = a;
            emit authorChanged();
        }
    }
    QString author() const {
        return m_author;
    }
signals:
    void authorChanged();
private:
    QString m_author;
};
#endif

main.cpp

#include <QtGui/QGuiApplication>
#include <QtQml/QQmlContext>
#include <QQmlEngine>
#include <QQmlComponent>
#include "message.h"



int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);


    QQmlEngine *engine = new QQmlEngine;
    Message msg;

    engine->rootContext()->setContextProperty("msg", &msg);
    QQmlComponent component(&engine, QUrl::fromLocalFile("qml/untitled3/main.qml"));
    component.create();



    return app.exec();
}
Reply all
Reply to author
Forward
0 new messages