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
}
}
}