從 C 建立 QtQuick 檢視
可以直接從 C++建立 QtQuick 檢視並公開 QML C++定義的屬性。在下面的程式碼中,C++程式建立了一個 QtQuick 檢視,並將檢視的高度和寬度作為屬性公開給 QML。
main.cpp 中
#include <QApplication>
#include <QQmlContext>
#include <QQuickView>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// Creating the view and manually setting the QML file it should display
QQuickView view;
view.setSource(QStringLiteral("main.qml"));
// Retrieving the QML context. This context allows us to expose data to the QML components
QQmlContext* rootContext = view.rootContext();
// Creating 2 new properties: the width and height of the view
rootContext->setContextProperty("WINDOW_WIDTH", 640);
rootContext->setContextProperty("WINDOW_HEIGHT", 360);
// Let's display the view
view.show();
return app.exec();
}
main.qml
import QtQuick 2.0
Rectangle {
// We can now access the properties we defined from C++ from the whole QML file
width: WINDOW_WIDTH
height: WINDOW_HEIGHT
Text {
text: qsTr("Hello World")
anchors.centerIn: parent
}
}