QML之混合编程:QQmlContext(一)

QML之混合编程:QQmlContext(一)

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 {
        objectName: "rectangle"
        width: 200; height: 100
        color: myBackgroundColor

        Text {
            id: textField
            anchors.centerIn: parent
            font.pixelSize: 18
            text: myText
        }

        MouseArea {
            anchors.fill: parent
            onClicked: {
                application.quit();
            }
        }
    }
}

上下文对象

// myclass.h
#include <QObject>
#include <QColor>
class MyClass : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QColor myColor MEMBER m_color NOTIFY colorChanged)
    Q_PROPERTY(QString myText MEMBER m_text NOTIFY textChanged)

public:
    explicit MyClass(QObject* parent = nullptr);

signals:
    void colorChanged();
    void textChanged(const QString &newText);

private:
    QColor m_color;
    QString m_text;
};

// main.cpp
context->setContextObject(&myClass);

注意,这与使用setContextProperty公开对象不同。当您使用setContextProperty公开一个对象时,该对象本身在QML中是可用的,就像前面示例中的“application”一样。如前所述,使用setContextObject公开对象时,只有上下文的属性可用。

何用C++数据填充一个简单的QStringList,并通过将其暴露给QML上下文在QML中使用它。

QStringList myList;
myList.append("Dog");
myList.append("Cat");
myList.append("Mouse");
myList.append("Dolphin");

QQmlApplicationEngine engine;
QQmlContext* context(engine.rootContext());
context->setContextProperty("myModel", QVariant::fromValue(myList));

   
ListView {
    width: 200; height: 200
    anchors.fill: parent

    model: myModel
    delegate: Rectangle {
        height: 30; width: 200
        Text {
            text: model.modelData
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值