QML之C++混合程式設計

LW0218發表於2020-12-17

QML之C++混合程式設計

QML訪問C++

上下文屬性

例如:
// main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QColor>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    QQmlContext* context = engine.rootContext();
    context->setContextProperty("myBackgroundColor", QColor(Qt::yellow));
    context->setContextProperty("myText", "I'm text from C++!");
    
    context->setContextProperty("application", &app);

    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    if (engine.rootObjects().isEmpty())
        return -1;
    
    return app.exec();
}

// main.qml
import QtQuick 2.9
import QtQuick.Window 2.3

Window {
    width: 640; height: 480; visible: true

    Rectangle {
        objectNam

相關文章