Qt quick project - how to invoke cpp function in qml file?
I' ve created quick project in Qt, selected from wizard at the begin, when Qt creator is started. Qt creator create project. There are qmlapplicationvierwer subproject and qml files in main project. I want to add new cpp source and header files (MainMenu.cpp and MainMenu.h) to project and then invoke function from these files in main.qml file. How I can register new type in qmlapplica开发者_运维百科tionviewer and invoke function from ManiMenu ?
qmlapplicationvierwer has only few function:
QApplication app(argc, argv);
QmlApplicationViewer viewer;
viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
viewer.setMainQmlFile(QLatin1String("qml/PUTest/main.qml"));
viewer.showExpanded();
return app.exec();
and:
viewer.addImportPath(const string &path);
Better way is not create project without project wizard ?
Thanks
Normally, you use this wizard to create QML only projects. The QmlApplication viewer is just a lightweight C++ wrapper around your QML file so a binary is generated and the QML file is loaded.
There's not much magic to do that on your own, see:
https://doc.qt.io/archives/qt-4.7/qtbinding.html
#include <QApplication>
#include <QDeclarativeView>
#include <QDeclarativeContext>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QDeclarativeView view;
QDeclarativeContext *context = view.rootContext();
context->setContextProperty("backgroundColor",
QColor(Qt::yellow));
view.setSource(QUrl::fromLocalFile("main.qml"));
view.show();
return app.exec();
}
And with setContextProperty you can ad global QML types via cpp...
Of course you can also reuse the QmlApplicationViewer. The Mainclass QmlApplicationViewer is derived from QDeclarativeView, so you directly have access to the context in this class.
So like in the example above, it should be possible to use:
QDeclarativeContext *context = this.rootContext();
context->setContextProperty("backgroundColor", QColor(Qt::yellow));
somewhere in the QmlApplicationViewer costructor or afterwards (didn't try it for now, let me know if it doesn't work).
精彩评论