加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

将Q_GADGET作为信号参数从C传递到QML

发布时间:2020-12-16 09:58:39 所属栏目:百科 来源:网络整理
导读:无法在QML代码中获取C对象的属性. 对象作为参数传递给信号. 期望在QML中,可以提取Record对象的属性文本.值应为abc. QML将对象视为QVariant(Record),其属性文本为undefined. Record是一个类似QPoint的值类型,因此它使用Q_GADGET声明. HPP: #ifndef LISTENP_H
无法在QML代码中获取C对象的属性.
对象作为参数传递给信号.

期望在QML中,可以提取Record对象的属性文本.值应为abc. QML将对象视为QVariant(Record),其属性文本为undefined.

Record是一个类似QPoint的值类型,因此它使用Q_GADGET声明.

HPP:

#ifndef LISTENP_HPP_
#define LISTENP_HPP_

#include <QObject>

#include "Record.hpp"

class ListenP: public QObject
{
Q_OBJECT

public:
    ListenP();
    virtual ~ListenP();

    void emitGotRecord();

signals:
    void gotRecord(Record r);
};

#endif /* LISTENP_HPP_ */

CPP:

#include "ListenP.hpp"

ListenP::ListenP() :
        QObject()
{
}

ListenP::~ListenP()
{
}

void ListenP::emitGotRecord()
{
    emit gotRecord(Record("abc"));
}

hpp for Record:

#ifndef RECORD_HPP_
#define RECORD_HPP_

#include <QObject>
#include <QMetaType>

class Record
{
Q_GADGET

Q_PROPERTY(QString text READ text WRITE setText)

public:
    Record(const QString& text = "");
    ~Record();

    QString text() const
    {
        return m_text;
    }

    void setText(const QString& text)
    {
        m_text = text;
    }

private:
    QString m_text;
};

Q_DECLARE_METATYPE(Record)

#endif /* RECORD_HPP_ */

记录的cpp:

#include "Record.hpp"

Record::Record(const QString& text) :
        m_text(text)
{
}

Record::~Record()
{
}

namespace
{
const int RecordMetaTypeId = qMetaTypeId<Record>();
}

QML篇:

Connections {
    target: listenPModel
    onGotRecord: {
        console.log(r)
        console.log(r.text)
    }
}

主要部分:

QGuiApplication app(argc,argv);

auto listenP = std::make_shared<ListenP>();
QQuickView view;
view.rootContext()->setContextProperty("listenPModel",&*listenP);
view.setSource(QStringLiteral("src/qml/main.qml"));
view.show();

QtConcurrent::run([=]
{
    QThread::sleep(3);
    listenP->emitGotRecord();
});

return app.exec();

日志显示:

qml: QVariant(Record)
qml: undefined

解决方法

Qt 5.5的 release notes表示新功能:

  • Qt Core
    • You can now have Q_PROPERTY and Q_INVOKABLE within a Q_GADGET,and there is a way to query the QMetaObject of such gadget using the QMetaType system

实际上,使用Qt 5.4编译和运行您的示例会得到与您相同的结果,而使用Qt 5.5,我得到了正确识别的记录,即我得到了结果:

qml: Record(abc)
qml: abc

此外,如Q_DECLARE_METATYPE documentation中所述,传递给宏的类型 – 在本例中为Record,应提供(1)公共默认构造函数,(2)公共复制构造函数和(3)公共析构函数.由于Record是一个非常简单的类,因此不需要提供复制构造函数,因为默认值就足够了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读