溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何利用上下文屬性將?C++?對(duì)象嵌入?QML?里

發(fā)布時(shí)間:2021-12-15 18:02:13 來(lái)源:億速云 閱讀:287 作者:柒染 欄目:開(kāi)發(fā)技術(shù)

本篇文章為大家展示了如何利用上下文屬性將 C++ 對(duì)象嵌入 QML 里,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

一、設(shè)置簡(jiǎn)單的上下文屬性

例如,這里有一個(gè) QML 項(xiàng),它引用了當(dāng)前作用域中不存在的 currentDateTime 值:

// MyItem.qml
import QtQuick 2.0
 
Text 
{ 
    text: currentDateTime 
}

這個(gè)值可以由加載 QML 組件的 C++ 應(yīng)用程序使用 QQmlContext::setContextProperty() 直接設(shè)置:

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

由于在 QML 中計(jì)算的所有表達(dá)式都是在特定上下文中計(jì)算的,如果修改了上下文,則將重新計(jì)算該上下文中的所有綁定。因此,應(yīng)在應(yīng)用程序初始化之外謹(jǐn)慎使用上下文屬性,因?yàn)檫@可能會(huì)導(dǎo)致應(yīng)用程序性能下降。

二、將對(duì)象設(shè)置為上下文屬性

上下文屬性可以包含 QVariant QObject* 值。 這意味著也可以使用這種方法注入自定義 C++ 對(duì)象,并且可以直接在 QML 中修改和讀取這些對(duì)象。修改上面的例子,嵌入一個(gè) QObject 實(shí)例而不是一個(gè) QDateTime 值,QML 代碼在對(duì)象實(shí)例上調(diào)用一個(gè)方法:

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

請(qǐng)注意:從 C++ 返回到 QML 的日期/時(shí)間值可以通過(guò) Qt.formatDateTime() 和相關(guān)函數(shù)進(jìn)行格式化。

如果 QML 項(xiàng)需要從上下文屬性接收信號(hào),它可以使用 Connections 類(lèi)型連接到它們。 例如,如果 ApplicationData 有一個(gè)名為 dataChanged() 的信號(hào),則可以使用 Connections 對(duì)象中的 onDataChanged 處理程序連接到該信號(hào):

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

如何利用上下文屬性將?C++?對(duì)象嵌入?QML?里

3.2、對(duì)象列表模型

#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++?對(duì)象嵌入?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++?對(duì)象嵌入?QML?里

上述內(nèi)容就是如何利用上下文屬性將 C++ 對(duì)象嵌入 QML 里,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI