Is it possible to transmit pointer to model from C++ to Qt Quick TableView?

不打扰是莪最后的温柔 提交于 2019-12-23 01:35:06

问题


I have class with QSqlDatabase and with pointer to QSqlTableModel in one class. I use pointer to QSqlTableModel, because initialization of database is going on in constructor and after that I create QSqlTableModel using this database (also in constructor but in heap already).
This class is registered type in qml and so I create it in QML. How is it better to point out TableView to the QSqlTableModel pointer of this class? If it is possible.


回答1:


It is not entirely clear what you're asking. I'm going to assume you want to share a pointer to your model with QML.

  1. Have a Q_PROPERTY for it. All Q_PROPERTYs are automatically visible to QML.

    • When returning QSqlTableModel* you need to register that type, too. E.g.

      qmlRegisterUncreatableType<QSqlTableModel>(
          "NameOfModuleInQML", 1, 0, "QSqlTableModel",
          "Cannot instanciate QSqlTableModel from QML");
      
    • Note that you cannot do this then:

      property QSqlTableModel mytabmodel
      

      do this instead if you need to:

      property QtObject mytabmodel
      
  2. Return it from a method of a class registered with QML (note that you must return QObject*). This is very likely what you want. E.g.

     class SomeClass : public QObject {
          // ...
     public:
         Q_INVOKABLE QObject *model() {
              return tableModel;
         }
         // ...
     };
    

    Then you can do this in QML:

    TableView {
        model: instanceOfYourclass.model()
        // other bindings
    
        TableViewColumn {
            title: qsTr("Name")
            role: "Name"
            width: 150
        }
    
        // and so on
    }
    
  3. You can create a singleton

    QObject *tableModelProvider(QQmlEngine *engine, QJSEngine *scriptEngine)
    {
        (void)engine;
        (void)scriptEngine;
    
        return new QSqlTableModel(...);
    }
    
    qmlRegisterSingletonType<QSqlTableModel>("NameOfModule", 1, 0, "NameInQML", tableModelProvider);
    

    This is a suitable approach if there is and ever will be only one instance of your model and if you don't need much to initialize it.

  4. Set your model as a context property

     QQmlEngine engine;
    
     // ..
     engine.rootContext()->setContextProperty("nameInQml", yourTableModelInstance);
    


来源:https://stackoverflow.com/questions/26322897/is-it-possible-to-transmit-pointer-to-model-from-c-to-qt-quick-tableview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!