Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. QML and Qt Quick
  4. Ask help about Mysql query in QML
Forum Updated to NodeBB v4.3 + New Features

Ask help about Mysql query in QML

Scheduled Pinned Locked Moved Unsolved QML and Qt Quick
3 Posts 2 Posters 224 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Y Offline
    Y Offline
    Yang Yi
    wrote on 20 Nov 2022, 09:56 last edited by
    #1

    Hello everyone
    I just start learning QML. I meet a problem. In C++, I use the mysql database, and in the QML, I hope to get the query result data value of the certain index.

    This is my c++ code
    (1) MySQLQuery class

    class MySQLQuery : public QSqlQueryModel
    {
    Q_OBJECT
    Q_PROPERTY(QString query READ queryStr WRITE setQueryStr NOTIFY queryStrChanged)
    Q_PROPERTY(QStringList userRoleNames READ userRoleNames CONSTANT)

    public:
    using QSqlQueryModel::QSqlQueryModel;
    QHash<int, QByteArray> roleNames() const
    {
    QHash<int, QByteArray> roles;
    for (int i = 0; i < record().count(); i ++) {
    roles.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8());
    }
    return roles;
    }

    QVariant data(const QModelIndex &index, int role) const
    {
        QVariant value;
        if (index.isValid()) {
            if (role < Qt::UserRole) {
                value = QSqlQueryModel::data(index, role);
            } else {
                int columnIdx = role - Qt::UserRole - 1;
                QModelIndex modelIndex = this->index(index.row(), columnIdx);
                value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
            }
        }
        return value;
    }
    
    QString queryStr() const{
        return query().lastQuery();
    }
    
    void setQueryStr(const QString &query){
        if(queryStr() == query)
            return;
        setQuery(query);
        emit queryStrChanged();
    }
    
    QStringList userRoleNames() const {
        QStringList names;
        for (int i = 0; i < record().count(); i ++) {
            names << record().fieldName(i).toUtf8();
        }
        return names;
    }
    

    signals:
    void queryStrChanged();
    };

    (2) main.cpp

    int main(int argc, char *argv[])
    {
    #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    #endif
    QGuiApplication app(argc, argv);

    // qmlRegisterType<MySQLService>("MySQLAdd",1,0,"MySQLAdd");

    bool a = sqlConnection();
    qmlRegisterType<MySQLQuery>("MySQLQuery", 1, 0, "MySQLQuery");

    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);
    
    
    
    
    return app.exec();
    

    }

    The following is my QML:

    import QtQuick 2.15
    import QtQuick.Window 2.15
    import QtQuick.Controls 2.15
    import QtMultimedia 5.15
    import MySQLQuery 1.0
    Window {
    id: mainWin
    width: 1080
    height: 768
    visible: true

    MySQLQuery{
    id: main_SQLquery
    query:mainStr_SQLquery
    }

    Timer{
        id:timer_coal_counter
        interval: 1000
        running: true
        repeat:true
        onTriggered: {
            mainStr_coal_SQLquery = "select * from coal_level where camera_id = 0 order by time desc LIMIT 0, 1"
           console.log("-----------", main_coal_SQLquery.rowCount())
    
            console.log("-----------", main_coal_SQLquery.record(0).value("camera_id").toInt())
    
        }
    

    }

    There is mistake that "TypeError: Property 'record' of object MySQLQuery(0x1b33108a880) is not a function"

    I checked the record is the function of QSqlQueryModel, and MySQLQuery is a class of QSqlQueryModel

    Could you kindly to help me. Thank you very much

    J 1 Reply Last reply 20 Nov 2022, 10:24
    0
    • Y Yang Yi
      20 Nov 2022, 09:56

      Hello everyone
      I just start learning QML. I meet a problem. In C++, I use the mysql database, and in the QML, I hope to get the query result data value of the certain index.

      This is my c++ code
      (1) MySQLQuery class

      class MySQLQuery : public QSqlQueryModel
      {
      Q_OBJECT
      Q_PROPERTY(QString query READ queryStr WRITE setQueryStr NOTIFY queryStrChanged)
      Q_PROPERTY(QStringList userRoleNames READ userRoleNames CONSTANT)

      public:
      using QSqlQueryModel::QSqlQueryModel;
      QHash<int, QByteArray> roleNames() const
      {
      QHash<int, QByteArray> roles;
      for (int i = 0; i < record().count(); i ++) {
      roles.insert(Qt::UserRole + i + 1, record().fieldName(i).toUtf8());
      }
      return roles;
      }

      QVariant data(const QModelIndex &index, int role) const
      {
          QVariant value;
          if (index.isValid()) {
              if (role < Qt::UserRole) {
                  value = QSqlQueryModel::data(index, role);
              } else {
                  int columnIdx = role - Qt::UserRole - 1;
                  QModelIndex modelIndex = this->index(index.row(), columnIdx);
                  value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
              }
          }
          return value;
      }
      
      QString queryStr() const{
          return query().lastQuery();
      }
      
      void setQueryStr(const QString &query){
          if(queryStr() == query)
              return;
          setQuery(query);
          emit queryStrChanged();
      }
      
      QStringList userRoleNames() const {
          QStringList names;
          for (int i = 0; i < record().count(); i ++) {
              names << record().fieldName(i).toUtf8();
          }
          return names;
      }
      

      signals:
      void queryStrChanged();
      };

      (2) main.cpp

      int main(int argc, char *argv[])
      {
      #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
      QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
      #endif
      QGuiApplication app(argc, argv);

      // qmlRegisterType<MySQLService>("MySQLAdd",1,0,"MySQLAdd");

      bool a = sqlConnection();
      qmlRegisterType<MySQLQuery>("MySQLQuery", 1, 0, "MySQLQuery");

      QQmlApplicationEngine engine;
      const QUrl url(QStringLiteral("qrc:/main.qml"));
      QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                       &app, [url](QObject *obj, const QUrl &objUrl) {
          if (!obj && url == objUrl)
              QCoreApplication::exit(-1);
      }, Qt::QueuedConnection);
      engine.load(url);
      
      
      
      
      return app.exec();
      

      }

      The following is my QML:

      import QtQuick 2.15
      import QtQuick.Window 2.15
      import QtQuick.Controls 2.15
      import QtMultimedia 5.15
      import MySQLQuery 1.0
      Window {
      id: mainWin
      width: 1080
      height: 768
      visible: true

      MySQLQuery{
      id: main_SQLquery
      query:mainStr_SQLquery
      }

      Timer{
          id:timer_coal_counter
          interval: 1000
          running: true
          repeat:true
          onTriggered: {
              mainStr_coal_SQLquery = "select * from coal_level where camera_id = 0 order by time desc LIMIT 0, 1"
             console.log("-----------", main_coal_SQLquery.rowCount())
      
              console.log("-----------", main_coal_SQLquery.record(0).value("camera_id").toInt())
      
          }
      

      }

      There is mistake that "TypeError: Property 'record' of object MySQLQuery(0x1b33108a880) is not a function"

      I checked the record is the function of QSqlQueryModel, and MySQLQuery is a class of QSqlQueryModel

      Could you kindly to help me. Thank you very much

      J Online
      J Online
      JonB
      wrote on 20 Nov 2022, 10:24 last edited by JonB
      #2

      @Yang-Yi
      Please use the forum's Code tags to enclose blocks of code for people to read.

      I know little about QML. And I am not sure that it would the cause the "Property 'record' of object MySQLQuery(0x1b33108a880) is not a function" you report, that may come from elsewhere. BUT

              mainStr_coal_SQLquery = "select * from coal_level where camera_id = 0 order by time desc LIMIT 0, 1"
             console.log("-----------", main_coal_SQLquery.rowCount())
      
              console.log("-----------", main_coal_SQLquery.record(0).value("camera_id").toInt())
      

      mainStr_coal_SQLquery seems to be a (JavaScript?) string. How can you access main_coal_SQLquery.rowCount() or main_coal_SQLquery.record(0) from a string?

      Y 1 Reply Last reply 21 Nov 2022, 00:55
      0
      • J JonB
        20 Nov 2022, 10:24

        @Yang-Yi
        Please use the forum's Code tags to enclose blocks of code for people to read.

        I know little about QML. And I am not sure that it would the cause the "Property 'record' of object MySQLQuery(0x1b33108a880) is not a function" you report, that may come from elsewhere. BUT

                mainStr_coal_SQLquery = "select * from coal_level where camera_id = 0 order by time desc LIMIT 0, 1"
               console.log("-----------", main_coal_SQLquery.rowCount())
        
                console.log("-----------", main_coal_SQLquery.record(0).value("camera_id").toInt())
        

        mainStr_coal_SQLquery seems to be a (JavaScript?) string. How can you access main_coal_SQLquery.rowCount() or main_coal_SQLquery.record(0) from a string?

        Y Offline
        Y Offline
        Yang Yi
        wrote on 21 Nov 2022, 00:55 last edited by
        #3

        @JonB. Thank you very much. I am very glad you can give me help.

        I can get the result of:

         console.log("========", main_coal_SQLquery.rowCount())
        

        but I can not the the result of

        console.log("========", main_coal_SQLquery.record(0))
        

        The mistake is "TypeError: Property 'record' of object MySQLQuery(0x18692474a90) is not a function"

        1 Reply Last reply
        0

        1/3

        20 Nov 2022, 09:56

        • Login

        • Login or register to search.
        1 out of 3
        • First post
          1/3
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved