Is it possible to transmit pointer to model from C

2019-06-02 18:09发布

问题:

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);
    


标签: qml qt5 qtquick2