Frage

Thanks to Jay, the problem seems not to be with QML but only in the database.

So a minimal erroneous code would be :

QFile::remove("my.db.sqlite");

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("my.db.sqlite");
db.open();

QSqlQuery drop("drop table List;");
QSqlQuery create("create table List (sample_text char(200));");
QSqlQuery insert("insert into List values (\"some message!\");");

drop.exec();
create.exec();
insert.exec();

db.close();

When inspecting my.db.sqlite, I get :

sqlite> select * from list;
some message!
some message!

Thanks!

------ Old question -------

I am in the process of learning both QtSql and QML, so there is some room for errors. Pretty much my whole problem is in the title of my question. I tried to make a short, self-contained code to reproduce it :

C++ code :

int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer viewer;
    // uncomment after first launch, deleted test to make code short
// QFile::remove("my.db.sqlite"); 

QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("my.db.sqlite");
db.open();

QSqlQuery create("create table List (sample_text char(200))");
QSqlQuery create2("insert into List values (\"message !\")");
create.exec();
create2.exec();

QSqlQueryModel *someSqlModel = new QSqlQueryModel();
someSqlModel->setQuery("SELECT * FROM List");

QQmlContext *context = viewer.rootContext();
context->setContextProperty("datamodel", someSqlModel);

viewer.setMainQmlFile(QStringLiteral("qml/test/main.qml"));
viewer.showExpanded();

return app.exec();
}

QML Code :

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

I should get "message !" as output in my list, but I get :

message !

message !

Any help ? Thanks!

War es hilfreich?

Lösung

Okay, finally I found the error.

According to this bug report :

https://bugreports.qt-project.org/browse/QTBUG-30205

You should not call exec() if you put the query in the constructor of QSqlQuery.

Andere Tipps

I think your sqllite database contains multiple records.

If you run this app multiple times I would think the table create would fail, then it would insert another row, then it would display the multiple rows.

You can use the sqlite command line application to verify the content of your database.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top