服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - 利用上下文属性将 C++ 对象嵌入 QML 里

利用上下文属性将 C++ 对象嵌入 QML 里

2022-07-13 09:37友善啊,朋友 C/C++

这篇文章主要介绍了利用上下文属性将 C++ 对象嵌入 QML里,将 QML 对象加载到 C++ 应用程序中时,直接嵌入一些可在 QML 代码中使用的 C++ 数据会很有用。例如,这使得在嵌入对象上调用 C++ 方法或使用 C++ 对象实例作为 QML 视图的数据模

QQmlContext 类使将 C++ 数据注入 QML 对象的能力成为可能。此类向 QML 对象的上下文公开数据,以便可以直接从 QML 代码范围内引用数据。

 

一、设置简单的上下文属性

例如,这里有一个 QML 项,它引用了当前作用域中不存在的 currentDateTime 值:

// MyItem.qml
import QtQuick 2.0

Text 
{ 
  text: currentDateTime 
}


这个值可以由加载 QML 组件的 C++ 应用程序使用 QQmlContext::setContextProperty() 直接设置:

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


由于在 QML 中计算的所有表达式都是在特定上下文中计算的,如果修改了上下文,则将重新计算该上下文中的所有绑定。因此,应在应用程序初始化之外谨慎使用上下文属性,因为这可能会导致应用程序性能下降。

 

二、将对象设置为上下文属性

上下文属性可以包含 QVariant 或 QObject* 值。 这意味着也可以使用这种方法注入自定义 C++ 对象,并且可以直接在 QML 中修改和读取这些对象。修改上面的例子,嵌入一个 QObject 实例而不是一个 QDateTime 值,QML 代码在对象实例上调用一个方法:

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() 和相关函数进行格式化。

如果 QML 项需要从上下文属性接收信号,它可以使用 Connections 类型连接到它们。 例如,如果 ApplicationData 有一个名为 dataChanged() 的信号,则可以使用 Connections 对象中的 onDataChanged 处理程序连接到该信号:

Text 
{
  text: applicationData.getCurrentDateTime()

  Connections 
  {
      target: applicationData
      onDataChanged: console.log("The application data changed!")
  }
}

 

三、上下文属性与C++ 的数据模型示例

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

利用上下文属性将 C++ 对象嵌入 QML 里

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

利用上下文属性将 C++ 对象嵌入 QML 里

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

利用上下文属性将 C++ 对象嵌入 QML 里

到此这篇关于利用上下文属性将 C++ 对象嵌入 QML 里的文章就介绍到这了,更多相关  C++ 对象嵌入 QML 里内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/kenfan1647/article/details/12192475

延伸 · 阅读

精彩推荐
  • C/C++C++实现LeetCode(49.群组错位词)

    C++实现LeetCode(49.群组错位词)

    这篇文章主要介绍了C++实现LeetCode(49.群组错位词),本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下...

    Grandyang7062021-11-29
  • C/C++C语言实现简易网络聊天室

    C语言实现简易网络聊天室

    这篇文章主要为大家详细介绍了C语言实现简易网络聊天室,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    菠萝小马哥6742021-11-19
  • C/C++C++中字符串与整型及浮点型转换全攻略

    C++中字符串与整型及浮点型转换全攻略

    C++算法刷题等过程中经常会遇到字符串与数字类型的转换,在这其中虽然朴素的算法有不少,但是对于double等类型还是可以说遇到一些麻烦,所以今天就来...

    异想之旅8282022-01-05
  • C/C++深入解析C++和JAVA的字符串

    深入解析C++和JAVA的字符串

    这篇文章主要介绍了C++和JAVA的字符串,JAVA 中String 和StringBuffer的区别,需要的朋友可以参考下...

    padden11802021-03-04
  • C/C++C++中的string类型

    C++中的string类型

    这篇文章主要介绍了C++中的string类型,在C++当中,除了char 类型,还有专门的字符串类型,就叫做string,下面文字将围绕其相关资料展开详细内容,需要的朋...

    梁唐5982022-02-20
  • C/C++C++中函数使用的基本知识学习教程

    C++中函数使用的基本知识学习教程

    这篇文章主要介绍了C++中函数使用的基本知识学习教程,涵盖了函数的声明和参数以及指针等各个方面的知识,非常全面,需要的朋友可以参考下...

    C++教程网10572021-03-22
  • C/C++C++实现区块链的源码

    C++实现区块链的源码

    这篇文章主要介绍了C++实现区块链的源码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...

    程序小黑12602021-10-20
  • C/C++C语言 位段的详细介绍

    C语言 位段的详细介绍

    这篇文章主要介绍了C语言 位段的详细介绍的相关资料,学习C语言基础的朋友,可以参考本文,需要的朋友可以参考下...

    海 子9582021-04-20