草庐IT

javascript - 仅在通过脚本访问时未定义属性

coder 2025-01-18 原文

我遇到了一些奇怪的行为,其中可以通过 QObjectproperty 函数直接访问属性,但不能通过 JavaScript:

#include <QApplication>
#include <QDebug>
#include <QScriptEngine>
#include <QStringList>

class Item : public QObject
{
    Q_OBJECT
public:
    Q_PROPERTY(int typeId READ typeId)
    Q_PROPERTY(int usesLeft READ usesLeft)

    Item() :
        mTypeId(0),
        mUsesLeft(-1)
    {
    }

    Item(int typeId) :
        mTypeId(typeId)
    {
        if (typeId != 0) {
            mUsesLeft = 5;
        }
    }

    Item(const Item &item) :
        QObject(0)
    {
        *this = item;
    }

    ~Item()
    {
    }

    Item& operator=(const Item& rhs)
    {
        mTypeId = rhs.mTypeId;
        mUsesLeft = rhs.mUsesLeft;
        return *this;
    }

    int typeId() const { return mTypeId; }

    int usesLeft() const { return mUsesLeft; }
    void setUsesLeft(int usesLeft) { mUsesLeft = usesLeft; }

    friend QDataStream &operator<<(QDataStream &out, const Item &item);
    friend QDataStream &operator>>(QDataStream &in, Item &item);
    friend QDebug operator<<(QDebug debug, const Item &item);
private:
    int mTypeId;
    int mUsesLeft;
};

QDataStream &operator<<(QDataStream &out, const Item &item)
{
    out << item.typeId()
        << item.usesLeft();
    return out;
}

QDataStream &operator>>(QDataStream &in, Item &item)
{
    in >> item.mTypeId
       >> item.mUsesLeft;
    return in;
}

QDebug operator<<(QDebug debug, const Item &item)
{
    debug.nospace() << "(Item typeId=" << item.typeId()
                    << ", usesLeft=" << item.usesLeft();
    return debug.space();
}

Q_DECLARE_METATYPE(Item)

class ItemStack : public QObject
{
    Q_OBJECT
public:
    Q_PROPERTY(Item *item READ item)
    Q_PROPERTY(int size READ size)

    ItemStack() :
        mSize(0)
    {
    }

    ItemStack(const ItemStack &rhs) :
        QObject()
    {
        *this = rhs;
    }

    ItemStack(const Item &item, int size) :
        mItem(item),
        mSize(size)
    {
    }

    ~ItemStack()
    {
    }

    ItemStack& operator=(const ItemStack& rhs)
    {
        if(this == &rhs) return *this;

        mItem = rhs.mItem;
        mSize = rhs.mSize;

        return *this;
    }

    Item* item()
    {
        return &mItem;
    }

    const Item *item() const
    {
        return &mItem;
    }

    int size() const
    {
        return mSize;
    }

    friend QDataStream &operator<<(QDataStream &out, const ItemStack &itemStack);
    friend QDataStream &operator>>(QDataStream &in, ItemStack &itemStack);
    friend QDebug operator<<(QDebug debug, const ItemStack &itemStack);
private:
    Item mItem;
    int mSize;
};

QDataStream &operator<<(QDataStream &out, const ItemStack &itemStack)
{
    out << *itemStack.item()
        << itemStack.size();
    return out;
}

QDataStream &operator>>(QDataStream &in, ItemStack &itemStack)
{
    in >> itemStack.mItem
       >> itemStack.mSize;
    return in;
}

QDebug operator<<(QDebug debug, const ItemStack &itemStack)
{
    debug.nospace() << "(ItemStack item=" << *itemStack.item()
                    << ", size=" << itemStack.size()
                    << ")";
    return debug.space();
}

Q_DECLARE_METATYPE(ItemStack)

class GunEntity : public QObject
{
    Q_OBJECT
public:
    Q_PROPERTY(ItemStack roundsLoaded READ roundsLoaded)

    GunEntity() : mRoundsLoaded(Item(1), 7) {}

    ItemStack roundsLoaded() { return mRoundsLoaded; }
private:
    ItemStack mRoundsLoaded;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // Accessing directly through properties.
    GunEntity ge;
    qDebug() << "Can convert ge.roundsLoaded to ItemStack?" << ge.property("roundsLoaded").canConvert<ItemStack>();
    ItemStack is = ge.property("roundsLoaded").value<ItemStack>();
    qDebug() << is;
    qDebug() << "Can convert is.item to Item?" << is.property("item").canConvert<Item*>();
    qDebug() << *is.property("item").value<Item*>();
    qDebug() << "Can convert is.size to int?" << is.property("size").canConvert<int>();
    qDebug() << is.property("size").toInt();

    // Accessing through QScriptEngine.
    QScriptEngine se;
    se.evaluate("function blah(gun) { print(gun.roundsLoaded); print(gun.roundsLoaded.item); print(gun.roundsLoaded.size); }");
    if (se.hasUncaughtException()) {
        qDebug() << se.uncaughtException().toString() << ":"
                 << se.uncaughtExceptionLineNumber() << se.uncaughtExceptionBacktrace();
    }
    QScriptValueList args;
    args << se.newQObject(&ge);
    QScriptValue ret = se.globalObject().property("blah").call(se.globalObject(), args);

    if (se.hasUncaughtException()) {
        qDebug() << se.uncaughtException().toString() << ":"
                 << se.uncaughtExceptionLineNumber() << se.uncaughtExceptionBacktrace();
    }

    return 0;
}

#include "main.moc"

我做错了什么?

最佳答案

我可以提出一些建议。

应设置对象名称。脚本中对象的名称就是这样设置的。

setObjectName( "Blah" );

我没有看到您在哪里实例化特定对象并将其告知脚本引擎:

   ScriptEngine->globalObject().setProperty( objectName(), ScriptEngine->newQObject( myObject, QScriptEngine::AutoOwnership, QScriptEngine::ExcludeSuperClassContents ) );

关于javascript - 仅在通过脚本访问时未定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16310311/

有关javascript - 仅在通过脚本访问时未定义属性的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  3. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  4. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  5. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  8. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  9. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  10. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

随机推荐