Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to embed C++ object in QML by using context attribute

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to use the context attribute to embed C++ objects into QML. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

First, set simple context properties

For example, there is a QML entry that references a currentDateTime value that does not exist in the current scope:

/ / MyItem.qmlimport QtQuick 2.0 Text {text: currentDateTime}

This value can be set directly by the C++ application that loads the QML component using QQmlContext::setContextProperty ():

QQuickView view; view.rootContext ()-> setContextProperty ("currentDateTime", QDateTime::currentDateTime ()); view.setSource (QUrl::fromLocalFile ("MyItem.qml")); view.show ()

Because all expressions evaluated in QML are evaluated in a specific context, if the context is modified, all bindings in that context are recalculated. Therefore, you should be careful to use context properties outside of application initialization, as this may result in application performance degradation.

Second, set the object to the context property

Context properties can contain QVariant or QObject* values. This means that custom C++ objects can also be injected using this method, and these objects can be modified and read directly in QML. Modify the above example to embed a QObject instance instead of a QDateTime value, and the QML code calls a method in the object instance:

Class ApplicationData: public QObject {Q_OBJECTpublic: 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.qmlimport QtQuick 2.0 Text {text: applicationData.getCurrentDateTime ()}

Note: the date / time value returned from C++ to QML can be formatted with Qt.formatDateTime () and related functions.

If the QML item needs to receive signals from the context property, it can connect to them using the Connections type. For example, if ApplicationData has a signal named dataChanged (), you can use the onDataChanged handler in the Connections object to connect to the signal:

Text {text: applicationData.getCurrentDateTime () Connections {target: applicationData onDataChanged: console.log ("The application data changed!")} 3. Example of context attribute and data model of C++, string list model 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}

Object list model # ifndef DATAOBJECT_H#define DATAOBJECT_H# include 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 dataobject.h DataObject::DataObject; QString masking color;}; # endif / / DATAOBJECT_H#include # include "dataobject.h" Color (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 masked 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 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. QAbstractItemModel#include # include class Animal {public: Animal (const QString & type, const QString & size); QString type () const; QString size () const; private: QString massively type; QString melesize;}; class AnimalModel: public QAbstractListModel {Q_OBJECTpublic: 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 roleNames () const; private: QList animals;}; # include "model.h" Animal::Animal (const QString & type, const QString & size): m_type (type), m_size (size) {} QString Animal::type () const {return masked 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 = 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 AnimalModel::roleNames () const {QHash 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: 250model: myModel delegate: Text {text: "Animal:" + type + "," + size}}

The above content is how to use the context attribute to embed C++ objects into QML. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report