标签:
在这篇文章中,我们将介绍如何在QML中使用C++代码。在以前的文章“ 使用C++拓展QML 类型及Property binding!”中,我们可以可以通过C++ plugin的方法来拓展我们的QML功能。那个项目是CMake项目。对于qmake项目来说,我们也可以做同样的事。可以使用一个plugin,并在QML中调用它。
今天,我们将不使用plugin的方法,我们希望在qmake项目中直接调用C++代码。那么我们将如何做呢?这里注意qmake只对15.04及以上的ubuntu手机target (模拟器及手机)适用。
TEMPLATE = app TARGET = trafficlight load(ubuntu-click) QT += core qml quick SOURCES += main.cpp trafficlight.cpp HEADERS += trafficlight.h RESOURCES += trafficlight.qrc OTHER_FILES += trafficlight.apparmor trafficlight.desktop trafficlight.png #specify where the config files are installed to config_files.path = /trafficlight config_files.files += $${OTHER_FILES} message($$config_files.files) INSTALLS+=config_files # Default rules for deployment. target.path = $${UBUNTU_CLICK_BINARY_PATH} INSTALLS+=target
QT += core qml quick
SOURCES += main.cpp trafficlight.cpp
HEADERS += trafficlight.h
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQuickView> #include <QQmlContext> #include <trafficlight.h> int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); qmlRegisterType<TrafficLight>("Light", 1,0, "TrafficLight"); int count = 3; QQuickView view; view.setSource(QUrl(QStringLiteral("qrc:///Main.qml"))); view.setResizeMode(QQuickView::SizeRootObjectToView); view.rootContext()->setContextProperty("total", QVariant::fromValue(count)); view.show(); return app.exec(); }
qmlRegisterType<TrafficLight>("Light", 1,0, "TrafficLight");
int count = 3; view.rootContext()->setContextProperty("total", QVariant::fromValue(count));
import QtQuick 2.0 import Ubuntu.Components 1.1 import Light 1.0 /*! \brief MainView with a Label and Button elements. */ MainView { // objectName for functional testing purposes (autopilot-qt5) objectName: "mainView" // Note! applicationName needs to match the "name" field of the click manifest applicationName: "trafficlight_new.liu-xiao-guo" /* This property enables the application to change orientation when the device is rotated. The default is false. */ //automaticOrientation: true // Removes the old toolbar and enables new features of the new header. useDeprecatedToolbar: false width: units.gu(60) height: units.gu(85) Page { title: i18n.tr("trafficlight") Column { anchors.centerIn: parent spacing: units.gu(3) Repeater { model: total delegate: TrafficLight { anchors.centerIn: parent.Center width: units.gu(20) height: width color: "red" } } } } }
import Light 1.0
TrafficLight { anchors.centerIn: parent.Center width: units.gu(20) height: width color: "red"
标签:
原文地址:http://blog.csdn.net/ubuntutouch/article/details/45664857