【问题标题】:How can I retrieve data from database in QML?如何从 QML 中的数据库中检索数据?
【发布时间】:2014-07-17 14:03:58
【问题描述】:

我正在尝试从 QML 中的数据库中检索数据。下面的代码在 Qt5 中有效,但我无法从 QML 访问数据。我得到:“未定义”。谁能帮帮我?

db.cpp

dataB = QSqlDatabase::addDatabase("QPSQL");

dataB.setHostName("192...");
dataB.setDatabaseName("database");
dataB.setPort(123);

dataB.setUserName("user1");
dataB.setPassword("user1");

this->model = new QSqlQueryModel();

model->setQuery("SELECT status FROM telephone");

ui->tableView->setModel(model);//result is in the first image

QQuickView *view = new QQuickView();

QQmlContext *context = view->rootContext();
context->setContextProperty("mySQLmodel", model);

view->setSource(QUrl("main.qml"));
view->show();

main.qml

Rectangle {
width: 300
height: 300

ListView {
    id: someListView
    anchors
    {
        fill: parent
 }
   model: mySQLmodel
    delegate: Label {
       text:{ "1 " + mySQLmodel.status}
   }

 }}

【问题讨论】:

    标签: database qt qml


    【解决方案1】:

    您应该尝试使用可以从 qml 访问的属性创建自己的 c++ 模型。然后你可以从你的数据库中填充你的模型。 看看你的模型的http://qt-project.org/doc/qt-4.8/qdeclarativemodels.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-26
      • 2013-10-31
      • 2016-11-27
      • 2016-03-17
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      相关资源
      最近更新 更多