QQmlContext类定义QML引擎内的上下文,上下文允许将数据公开给QML引擎实例化的QML组件。每个QQmlContext包含一组与其QObject属性不同的属性,这些属性允许将数据按名称显式绑定到上下文。 通过调用QQmlContext::setContextProperty()定义和更新上下文属性。
- QQmlContext::setContextProperty(const QString &name, const QVariant &value)
- QQmlContext::setContextProperty(const QString &name, QObject *value)
第一种是设置简单的QVariant数据,如int, QString等;第二种则是设置基于QObject的类实例。
第一种 - 设置QVariant为上下文属性
import QtQuick 2.9
Item
{
Rectangle
{
id: background;
width: parent.width;
height: 50;
radius: height / 8;
color: "blue";
anchors.centerIn: parent
Text
{
id: timer;
text: TestData;
font.pixelSize: 30
anchors.centerIn: background;
}
}
}
#include "widget.h"
#include "ui_widget.h"
#include <QQmlContext>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
ui->quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
ui->quickWidget->rootContext()->setContextProperty("TestData", "this is a test!");
ui->quickWidget->setSource(QUrl("qrc:/main.qml"));
}
Widget::~Widget()
{
delete ui;
}
第二种 - 设置对象为上下文属性
新建一个继承自QObject的类来获取当前时间,实例化后,通过设置上下文属性让qml代码获取到getCurrentDateTime()的返回值
#include <QObject>
#include <QDateTime>
class TimeData : public QObject
{
Q_OBJECT
public:
// 为了让QML代码成功的调用getCurrentDateTime()函数,最为关键的一点是用Q_INVOKABLE修饰
// 使用Q_INVOKABLE来修饰成员函数,目的在于被修饰的成员函数能够被元对象系统所唤起
Q_INVOKABLE QDateTime getCurrentDateTime()
{
return QDateTime::currentDateTime();
}
};
import QtQuick 2.9
Item {
Rectangle
{
id: background;
width: parent.width;
height: 50;
radius: height / 8;
color: "blue";
anchors.centerIn: parent
Text
{
id: timer;
text: TestData.getCurrentDateTime();
font.pixelSize: 30
anchors.centerIn: background;
}
}
}
#include "widget.h"
#include "ui_widget.h"
#include "TimeData.h"
#include <QQmlContext>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
TimeData data;
ui->quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
ui->quickWidget->rootContext()->setContextProperty("TestData", &data);
ui->quickWidget->setSource(QUrl("qrc:/main.qml"));
}
Widget::~Widget()
{
delete ui;
}