3

如何destroyed从 Qt Script 正确连接到 QObject 的信号?

当我像连接到您的平均信号一样连接它时,它不起作用。我确实测试了我删除了该对象并且其他 QObjects 确实收到了信号,但是我连接到它的脚本函数没有被调用。

以下是我用于测试的示例。最重要的部分是行:

_engine.evaluate("obj.destroyed.connect(function() { debug(\"obj destroyed\") })");

我希望它在obj被销毁时调用该函数。下面的代码确保在甚至循环已经开始时删除对象,并且它还测试对象确实向destroyed另一个 QObject 发送信号。我要修复的是脚本在发出信号debug("obj destroyed")后调用脚本函数。destroyed

ScriptTester.h:

#ifndef SCRIPTTESTER_H
#define SCRIPTTESTER_H

#include <QtScript>
#include <QtCore>

class ScriptTester: public QObject {
    Q_OBJECT

public:
    explicit ScriptTester(QObject *parent = 0);

private slots:
    void signalTest();
    void boo();

private:
    QScriptEngine _engine;
};

#endif // SCRIPTTESTER_H

ScriptTester.cpp:

#include "ScriptTester.h"

static QScriptValue scriptDebug(QScriptContext *context, QScriptEngine *engine) {
    Q_UNUSED(engine);
    if (context->argumentCount() >= 1) {
        QString msg = context->argument(0).toString();
        for (int i = 1; i < context->argumentCount(); ++i) {
            msg = msg.arg(context->argument(i).toString());
        }
        qDebug() << msg;
    }
    return QScriptValue();
}

ScriptTester::ScriptTester(QObject *parent) :
    QObject(parent)
{
    QTimer::singleShot(0, Qt::CoarseTimer, this, SLOT(signalTest()));
    _engine.globalObject().setProperty("debug", _engine.newFunction(scriptDebug, 1));
}

void ScriptTester::signalTest() {
    QObject *obj = new QObject(this);
    _engine.globalObject().setProperty("obj", _engine.newQObject(obj));
    _engine.evaluate("obj.destroyed.connect(function() { debug(\"obj destroyed\") })");
    if (_engine.hasUncaughtException()) {
        qDebug() << "Exception:" << _engine.uncaughtException().toString();
    }
    connect(obj, SIGNAL(destroyed()), this, SLOT(boo()));

    QTimer *timer = new QTimer;
    _engine.globalObject().setProperty("timer", _engine.newQObject(timer));
    _engine.evaluate("timer.timeout.connect(function() { debug(\"timer timeout\"); obj.deleteLater(); })");
    if (_engine.hasUncaughtException()) {
        qDebug() << "Exception:" << _engine.uncaughtException().toString();
    }

    timer->setSingleShot(true);
    timer->start(100);
}

void ScriptTester::boo() {
    qDebug() << "was destroyed!";
}

请注意,我不想要像destroyed首先传递给 C++ 代码然后手动或通过信号通知脚本那样的黑客攻击。我正在寻找一个完全在脚本中完成的实现。

4

0 回答 0