網(wǎng)站首頁 編程語言 正文
QQmlContext
類使將 C++ 數(shù)據(jù)注入 QML 對象的能力成為可能。此類向 QML 對象的上下文公開數(shù)據(jù),以便可以直接從 QML 代碼范圍內(nèi)引用數(shù)據(jù)。
一、設(shè)置簡單的上下文屬性
例如,這里有一個 QML 項,它引用了當(dāng)前作用域中不存在的 currentDateTime 值:
// MyItem.qml import QtQuick 2.0 Text { text: currentDateTime }
這個值可以由加載 QML 組件的 C++ 應(yīng)用程序使用 QQmlContext::setContextProperty()
直接設(shè)置:
QQuickView view; view.rootContext()->setContextProperty("currentDateTime",QDateTime::currentDateTime()); view.setSource(QUrl::fromLocalFile("MyItem.qml")); view.show();
由于在 QML 中計算的所有表達式都是在特定上下文中計算的,如果修改了上下文,則將重新計算該上下文中的所有綁定。因此,應(yīng)在應(yīng)用程序初始化之外謹慎使用上下文屬性,因為這可能會導(dǎo)致應(yīng)用程序性能下降。
二、將對象設(shè)置為上下文屬性
上下文屬性可以包含 QVariant
或 QObject*
值。 這意味著也可以使用這種方法注入自定義 C++ 對象,并且可以直接在 QML 中修改和讀取這些對象。修改上面的例子,嵌入一個 QObject 實例而不是一個 QDateTime
值,QML 代碼在對象實例上調(diào)用一個方法:
class ApplicationData : public QObject { Q_OBJECT public: Q_INVOKABLE QDateTime getCurrentDateTime() const { return QDateTime::currentDateTime(); } }; int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); ApplicationData data; QQuickView view; view.rootContext()->setContextProperty("applicationData", &data); view.setSource(QUrl::fromLocalFile("MyItem.qml")); view.show(); return app.exec(); } // MyItem.qml import QtQuick 2.0 Text { text: applicationData.getCurrentDateTime() }
請注意:從 C++ 返回到 QML 的日期/時間值可以通過 Qt.formatDateTime() 和相關(guān)函數(shù)進行格式化。
如果 QML 項需要從上下文屬性接收信號,它可以使用 Connections
類型連接到它們。 例如,如果 ApplicationData
有一個名為 dataChanged()
的信號,則可以使用 Connections
對象中的 onDataChanged
處理程序連接到該信號:
Text { text: applicationData.getCurrentDateTime() Connections { target: applicationData onDataChanged: console.log("The application data changed!") } }
三、上下文屬性與C++ 的數(shù)據(jù)模型示例
3.1、字符串列表模型
int main(int argc, char ** argv) { QGuiApplication app(argc, argv); QStringList dataList; dataList.append("Item 1"); dataList.append("Item 2"); dataList.append("Item 3"); dataList.append("Item 4"); QQuickView view; QQmlContext *ctxt = view.rootContext(); ctxt->setContextProperty("myModel", QVariant::fromValue(dataList)); view.setSource(QUrl("qrc:view.qml")); view.show(); return app.exec(); }
import QtQuick 2.0 ListView { width: 100; height: 100 model: myModel delegate: Rectangle { height: 25 width: 100 Text { text: modelData } } }
3.2、對象列表模型
#ifndef DATAOBJECT_H #define DATAOBJECT_H #include <QObject> class DataObject : public QObject { Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged) Q_PROPERTY(QString color READ color WRITE setColor NOTIFY colorChanged) public: DataObject(QObject *parent=nullptr); DataObject(const QString &name, const QString &color, QObject *parent=nullptr); QString name() const; void setName(const QString &name); QString color() const; void setColor(const QString &color); signals: void nameChanged(); void colorChanged(); private: QString m_name; QString m_color; }; #endif // DATAOBJECT_H
#include <QDebug> #include "dataobject.h" DataObject::DataObject(QObject *parent) : QObject(parent) { } DataObject::DataObject(const QString &name, const QString &color, QObject *parent) : QObject(parent), m_name(name), m_color(color) { } QString DataObject::name() const { return m_name; } void DataObject::setName(const QString &name) { if (name != m_name) { m_name = name; emit nameChanged(); } } QString DataObject::color() const { return m_color; } void DataObject::setColor(const QString &color) { if (color != m_color) { m_color = color; emit colorChanged(); } } #include "dataobject.h" int main(int argc, char ** argv) { QGuiApplication app(argc, argv); QList<QObject*> dataList; dataList.append(new DataObject("Item 1", "red")); dataList.append(new DataObject("Item 2", "green")); dataList.append(new DataObject("Item 3", "blue")); dataList.append(new DataObject("Item 4", "yellow")); QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView); QQmlContext *ctxt = view.rootContext(); ctxt->setContextProperty("myModel", QVariant::fromValue(dataList)); view.setSource(QUrl("qrc:view.qml")); view.show(); return app.exec(); } import QtQuick 2.0 ListView { width: 100; height: 100 model: myModel delegate: Rectangle { height: 25 width: 100 color: model.modelData.color Text { text: name } } }
3.3、QAbstractItemModel
#include <QAbstractListModel> #include <QStringList> class Animal { public: Animal(const QString &type, const QString &size); QString type() const; QString size() const; private: QString m_type; QString m_size; }; class AnimalModel : public QAbstractListModel { Q_OBJECT public: enum AnimalRoles { TypeRole = Qt::UserRole + 1, SizeRole }; AnimalModel(QObject *parent = nullptr); void addAnimal(const Animal &animal); int rowCount(const QModelIndex & parent = QModelIndex()) const; QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; protected: QHash<int, QByteArray> roleNames() const; private: QList<Animal> m_animals; };
#include "model.h" Animal::Animal(const QString &type, const QString &size) : m_type(type), m_size(size) { } QString Animal::type() const { return m_type; } QString Animal::size() const { return m_size; } AnimalModel::AnimalModel(QObject *parent) : QAbstractListModel(parent) { } void AnimalModel::addAnimal(const Animal &animal) { beginInsertRows(QModelIndex(), rowCount(), rowCount()); m_animals << animal; endInsertRows(); } int AnimalModel::rowCount(const QModelIndex & parent) const { Q_UNUSED(parent) return m_animals.count(); } QVariant AnimalModel::data(const QModelIndex & index, int role) const { if (index.row() < 0 || index.row() >= m_animals.count()) return QVariant(); const Animal &animal = m_animals[index.row()]; if (role == TypeRole) return animal.type(); else if (role == SizeRole) return animal.size(); return QVariant(); } QHash<int, QByteArray> AnimalModel::roleNames() const { QHash<int, QByteArray> roles; roles[TypeRole] = "type"; roles[SizeRole] = "size"; return roles; } int main(int argc, char ** argv) { QGuiApplication app(argc, argv); AnimalModel model; model.addAnimal(Animal("Wolf", "Medium")); model.addAnimal(Animal("Polar bear", "Large")); model.addAnimal(Animal("Quoll", "Small")); QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView); QQmlContext *ctxt = view.rootContext(); ctxt->setContextProperty("myModel", &model); view.setSource(QUrl("qrc:view.qml")); view.show(); return app.exec(); }
import QtQuick 2.0 ListView { width: 200; height: 250 model: myModel delegate: Text { text: "Animal: " + type + ", " + size } }
原文鏈接:https://blog.csdn.net/kenfan1647/article/details/12192475
相關(guān)推薦
- 2022-11-11 ASP.NET?MVC實現(xiàn)下拉框多選_實用技巧
- 2022-12-08 React狀態(tài)更新的優(yōu)先級機制源碼解析_React
- 2022-06-28 C語言多線程開發(fā)中死鎖與讀寫鎖問題詳解_C 語言
- 2022-03-31 React-Router6版本的更新引起的路由用法變化_React
- 2022-09-18 C#?中的partial?關(guān)鍵字詳解_C#教程
- 2023-01-03 Android?自定義Livedata使用示例解析_Android
- 2022-11-02 React循環(huán)遍歷渲染數(shù)組和對象元素方式_React
- 2022-08-14 Hyper-V設(shè)置虛擬機固定Ip的方法步驟_Hyper-V
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支