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.
Have a
Q_PROPERTY
for it. AllQ_PROPERTY
s 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
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 }
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.
Set your model as a context property
QQmlEngine engine; // .. engine.rootContext()->setContextProperty("nameInQml", yourTableModelInstance);