QML 报告引用错误:XYZ 未在添加到上下文C++对象上定义

QML reports ReferenceError: XYZ is not defined on C++ object added to context

本文关键字:上下文 C++ 对象 定义 添加 引用 报告 错误 XYZ QML      更新时间:2023-09-26

我最近开始学习QML(在很久以前尝试过之后(,我被困在代码与QML交互的方式Qt C++反之亦然。

我有一个Counter,它具有以下标题:

#include <QObject>
#include <QTimer>
class Counter : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int count
           READ getCount
           WRITE setCount
           NOTIFY signalCountChanged)
public:
    Counter(QObject *parent = Q_NULLPTR);
    int getCount();
    void setCount(int count);
signals:
    void signalCountChanged(int);
public slots:
    void slotStart();
private slots:
    void slotTimeout();
private:
    int count;
    QTimer *timer;
};

main.cpp如下:

#include <QtGui/QGuiApplication>
#include <QtQml/QQmlContext>
#include <QtGui/QGuiApplication>
#include <QtQuick/QQuickItem>
#include <QtQuick/QQuickView>
#include "counter.h"
int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    qmlRegisterType<Counter>("org.qmlplayground.counter", 0, 1, "Counter");
    QQuickView view;
    view.setSource(QUrl(QStringLiteral("qrc:/main.qml")));
    QObject *viewO = dynamic_cast<QObject*>(view.rootObject());
    Counter c;
    // Register Counter instance as "counter" property of top level context so that it can be accessed from within the QML code (for example: set the value count)
    view.rootContext()->setContextProperty("counter", &c);
    QObject::connect(viewO, SIGNAL(signalStartCounter()),
            &c, SLOT(slotStart()));
    QObject::connect(viewO, SIGNAL(signalQuit()), &app, SLOT(quit()));
    view.show();
    return app.exec();
}

最后是我QML的一部分(main.qml加载到QQuickView中,其余部分是 UI 表单(:

import QtQuick 2.7
import QtQuick.Window 2.2
// Importing some JavaScript files
import "qrc:/loggingFunctions.js" as LOG
import "qrc:/parseFunctions.js" as PARSE
// Importing a Qt C++ custom module
import org.qmlplayground.counter 0.1
MainForm {
    property int countState: counter.count // ERROR HERE
    signal signalStartCounter()
    signal signalQuit()
    anchors.fill: parent
    textInputMouseArea.onClicked: {
        LOG.logger("Clicked! Selecting all text in text input field", "N")
        textInput.selectAll()
    }
    textInput.onAccepted: {
        if(textInput.text === "quit") signalQuit()//Qt.quit();
        if(textInput.text === "help") textInput.text = LOG.logger("Displaying help", "H");
        var res = PARSE.parseInput(textInput.text);
        if(res && (typeof res === 'object') && res.constructor === Array) {
            switch(res[0]) {
            case "fact":
                labelOutput.text = res[1];
                break;
            case "count":
                counter.count = res[1];
                signalStartCounter();
                break;
            }
        }
    }
    onCountStateChanged:
        console.log("Hello")
    textInput.onTextChanged:
        console.log("Text changed");
}

如您所见,我已经测试了从QML发送到C++代码的两个信号,一个连接到QGuiApplication的插槽quit(),另一个连接到counter的插槽slotStart()。它工作正常。似乎这条线

counter.count = res[1];

不会导致任何问题(也许是因为它JS而不是QML?现在,我想读取Counter实例的count值并相应地更新我的 UI。如果我没记错的话,每个QML属性都会自动获得一些东西,其中之一是onChanged方法(事件处理程序或任何它的名字(。

但是当我运行我的代码时,我得到

`qrc:/main.qml:21: ReferenceError: counter is not defined

我以为做view->rootContext()->setContextProperty("counter", &c);就足够了,但似乎我错过了一些东西。因此,更普遍的问题是,如何正确地使C++对象在上下文QML可见。

这花了我大约 2 个小时才弄清楚(我在:D即将自杀时发布了我的问题(,但答案非常明显:我如何调用尚未初始化的属性?我的问题的解决方案基本上是在加载QML文件之前移动setContextProperty()

// ...
QQuickView view;
Counter c;
view.rootContext()->setContextProperty("counter", &c);
view.setSource(QUrl(QStringLiteral("qrc:/main.qml")));
// ...

通过这样做,该属性首先添加到view的根上下文中,然后加载其他QML内容,但counter属性仍然存在(。使用以前版本的代码,我基本上是在尝试在将QML文件添加为属性之前访问counter