Qt Script(三)

本文详细介绍了如何使用Qt Script与C++ API进行交互,包括如何封装本地函数、实现构造函数以及如何处理基于值类型的对象。通过示例展示了Person和Employee类的原型实现,并解释了如何为QPointF等值类型实现原型对象和构造函数。同时,还讨论了对象内存管理、翻译处理和ECMAScript兼容性的扩展功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Prototype-Based Programming with the Qt Script C++ API
用Qt Script C++API基于原型编程。
You can use QScriptEngine::newFunction() to wrap native functions. When implementing a constructor function, you also pass the prototype object as an argument to QScriptEngine::newFunction(). You can call QScriptValue::construct() to call a constructor function, and you can use QScriptValue::call() from within a native constructor function if you need to call a base class constructor.
你可以使用newFunction来封装本地函数。当实现一个构造函数的时候,你也可以传递原型对象作为newFunction()的参数。你可以调用construct()来调用一个构造函数并且你可以从一个本地构造函数中使用call()如果你需要调用一个基类构造函数。
The QScriptable class provides a convenient way to implement a prototype object in terms of C++ slots and properties. Take a look at the Default Prototypes Example to see how this is done. Alternatively, the prototype functionality can be implemented in terms of standalone native functions that you wrap with QScriptEngine::newFunction() and set as properties of your prototype object by calling QScriptValue::setProperty().
QScriptable类提供一种便捷的方式来实现原型对象根据C++槽和属性。看一个默认原型的例子是如何实现的。同样地原型功能可以被实现依据独立的本地函数,你可以用newFunction()封装并且设置原型对象的属性通过setProperty().
In the implementation of your prototype functions, you use QScriptable::thisObject() (or QScriptContext::thisObject()) to obtain a reference to the QScriptValue being operated upon; then you call qscriptvalue_cast() to cast it to your C++ type, and perform the relevant operations using the usual C++ API for the type.
在你的原型函数的实现中,乜可以使用QScriptable::thisObject()来获取一个将被操作的QScriptValue的引用;然后你调用qscriptvalue_cast强制转换成你自己的C++类型并且使用C++API执行相关的操作。
You associate a prototype object with a C++ type by calling QScriptEngine::setDefaultPrototype(). Once this mapping is established, Qt Script will automatically assign the correct prototype when a value of such a type is wrapped in a QScriptValue; either when you explicitly call QScriptEngine::toScriptValue(), or when a value of such a type is returned from a C++ slot and internally passed back to script code by the engine. This means you don’t have to implement wrapper classes if you use this approach
你可以通过调用setDefaultPrototype()来关联一个原型和C++类型。一旦这个映射被建立,Qt Script将自动分配正确的原型当这样一个类型的值封装在QScriptValue中,当你明确调用toScriptValue()或者当这样一个类型的值被从C++槽返回和在引擎内部传递的时候。如果你是用这种方法意味着你不必实现封装类。
As an example, let’s consider how the Person class from the preceding section can be implemented in terms of the Qt Script API. We begin with the native constructor function:
举个例子,让我们考虑前面的Person类如何依据Qt Script API实现。我们从本地构造函数开始:
QScriptValue Person_ctor(QScriptContext *context, QScriptEngine *engine)
{
QString name = context->argument(0).toString();
context->thisObject().setProperty(“name”, name);
return engine->undefinedValue();
}
Here’s the native equivalent of the Person.prototype.toString function we saw before:
这有一个我们之前看到的Person.prototype.toString等价的函数。
QScriptValue Person_prototype_toString(QScriptContext *context, QScriptEngine *engine)
{
QString name = context->thisObject().property(“name”).toString();
QString result = QString::fromLatin1(“Person(name: %0)”).arg(name);
return result;
}
The Person class can then be initialized as follows:
Person类可以向下面一样被初始化。
QScriptEngine engine;
QScriptValue ctor = engine.newFunction(Person_ctor);
ctor.property(“prototype”).setProperty(“toString”, engine.newFunction(Person_prototype_toString));
QScriptValue global = engine.globalObject();
global.setProperty(“Person”, ctor);
The implementation of the Employee subclass is similar. We use QScriptValue::call() to call the super-class (Person) constructor:
Employee子类的实现是类似的,我们使用call()来调用父类的构造函数
QScriptValue Employee_ctor(QScriptContext *context, QScriptEngine *engine)
{
QScriptValue super = context->callee().property(“prototype”).property(“constructor”);
super.call(context->thisObject(), QScriptValueList() << context->argument(0));
context->thisObject().setProperty(“salary”, context->argument(1));
return engine->undefinedValue();
}
The Employee class can then be initialized as follows:
Employee可以像下面一样被初始化。
QScriptValue empCtor = engine.newFunction(Employee_ctor);
empCtor.setProperty(“prototype”, global.property(“Person”).construct());
global.setProperty(“Employee”, empCtor);
When implementing the prototype object of a class, you may want to use the QScriptable class, as it enables you to define the API of your script class in terms of Qt properties, signals and slots, and automatically handles value conversion between the Qt Script and C++ side.
当实现一个类的原型时,你可能想使用QScriptable类,因为它能使你定义你自己脚本类的API依据Qt属性,信号,槽并且在Qt Script和C++之间自动处理值转换。
Implementing Prototype Objects for Value-based Types
对基于值的类型实现原型对象
When implementing a prototype object for a value-based type – e.g. QPointF – the same general technique applies; you populate a prototype object with functionality that should be shared among instances. You then associate the prototype object with the type by calling QScriptEngine::setDefaultPrototype(). This ensures that when e.g. a value of the relevant type is returned from a slot back to the script, the prototype link of the script value will be initialized correctly.
当实现基于值的原型对象时,QPointF,相同的一般技术应用。你可以用共享实例的功能填充原型对象。然后你使用setDefaultPrototype将原型对象和类型关联起来,这确保了当从一个槽返回一个跟类型关联的值到脚本的时候,脚本值连接的属性将被正确地初始化。
When values of the custom type are stored in QVariants – which Qt Script does by default –, qscriptvalue_cast() enables you to safely cast the script value to a pointer to the C++ type. This makes it easy to do type-checking, and, for prototype functions that should modify the underlying C++ value, lets you modify the actual value contained in the script value (and not a copy of it).
当自定义类型的值被存储在Qt Script默认的QVariant中时,qscriptvalue_cast使得你安全地将脚本值强转成一个指向C++类型的指针。这使得类型检查很容易并且对原型函数应该可以修改C++值,让你修改包含在脚本值中真实的值。
Q_DECLARE_METATYPE(QPointF)
Q_DECLARE_METATYPE(QPointF*)

QScriptValue QPointF_prototype_x(QScriptContext *context, QScriptEngine *engine)
{
// Since the point is not to be modified, it’s OK to cast to a value here
QPointF point = qscriptvalue_cast”<”QPointF”>”(context->thisObject());
return point.x();
}

QScriptValue QPointF_prototype_setX(QScriptContext *context, QScriptEngine *engine)
{
// Cast to a pointer to be able to modify the underlying C++ value
QPointF point = qscriptvalue_cast”<”QPointF“>”(context->thisObject());
if (!point)
return context->throwError(QScriptContext::TypeError, “QPointF.prototype.setX: this object is not a QPointF”);
point->setX(context->argument(0).toNumber());
return engine->undefinedValue();

}
Implementing Constructors for Value-based Types
对基于值的类型实现构造函数
You can implement a constructor function for a value-based type by wrapping a native factory function. For example, the following function implements a simple constructor for QPoint:
你可以实现一个对基于值类型的构造函数通过封装一个本地工厂函数。例如,下面的函数实现了一个QPoint的简单构造函数
QScriptValue QPoint_ctor(QScriptContext *context, QScriptEngine *engine)
{
int x = context->argument(0).toInt32();
int y = context->argument(1).toInt32();
return engine->toScriptValue(QPoint(x, y));
}

engine.globalObject().setProperty(“QPoint”, engine.newFunction(QPoint_ctor));
In the above code we simplified things a bit, e.g. we didn’t check the argument count to decide which QPoint C++ constructor to use. In your own constructors you have to do this type of resolution yourself, i.e. by checking the number of arguments passed to the native function, and/or by checking the type of the arguments and converting the arguments to the desired type. If you detect a problem with the arguments you may want to signal this by throwing a script exception; see QScriptContext::throwError().
在上面的代码中我们简单画一些事情,我们没有检查参数个数来决定调用那个QPoint的构造函数。在你自己的构造函数里你必须自己解决这个类型,通过检查传递给本地函数的参数数量或者通过检查参数的类型和转换参数到期望的类型。如果你检测到一个参数问题,你可能想通过抛出一个脚本异常来发信号;
Managing Non-QObject-based Objects
管理不是基于QObject的对象
For value-based types (e.g. QPoint), the C++ object will be destroyed when the Qt Script object is garbage-collected, so managing the memory of the C++ object is not an issue. For QObjects, Qt Script provides several alternatives for managing the underlying C++ object’s lifetime; see the Controlling QObject Ownership section. However, for polymorphic types that don’t inherit from QObject, and when you can’t (or won’t) wrap the type in a QObject, you have to manage the lifetime of the C++ object yourself.
对于基于值的类型,C++对象将被销毁当Qt Script对象被垃圾回收时,因此管理C++内存对象不是问题。对对象来说,Qt Script提供了一些管理C++对象的生命周期的替代选择。看控制QObject所有权的章节。然而对不继承自QObject的多态类型来说当你不能将类型封装在一个QObject中时,你必须管理C++对象的生命周期。
A behavior that’s often reasonable when a Qt Script object wraps a C++ object, is that the C++ object is deleted when the Qt Script object is garbage-collected; this is typically the case when the objects can be constructed by scripts, as opposed to the application providing the scripts with pre-made “environment” objects. A way of making the lifetime of the C++ object follow the lifetime of the Qt Script object is by using a shared pointer class, such as QSharedPointer, to hold a pointer to your object; when the Qt Script object containing the QSharedPointer is garbage-collected, the underlying C++ object will be deleted if there are no other references to the object.
当一个Qt Script对象封装一个C++对象的时候,通常合理的行为是C++对象被删除当Qt Script对象被垃圾回收的时候;这是典型的情况当对象用脚本构造,而不是应用程序提供给脚本的预制的环境对象。使得C++对象跟Qt Script对象一致的一种方法是使用一个共享指针类,比如QSharedPointer,保留一个指向你对象的指针,当包含QSharedPointer的Qt Script 对象被回收时,C++对象将被删除如果没有其他地方引用这个对象。
The following snippet shows a constructor function that constructs QXmlStreamReader objects that are stored using QSharedPointer:
下面的代码片段展示了一个构造QXmlStreamReader的构造函数使用QSharedPointer存储。
typedef QSharedPointer XmlStreamReaderPointer;

Q_DECLARE_METATYPE(XmlStreamReaderPointer)

QScriptValue constructXmlStreamReader(QScriptContext *context, QScriptEngine *engine)
{
if (!context->isCalledAsConstructor())
return context->throwError(QScriptContext::SyntaxError, “please use the ‘new’ operator”);

QIODevice *device = qobject_cast<QIODevice*>(context->argument(0).toQObject());
if (!device)
    return context->throwError(QScriptContext::TypeError, "please supply a QIODevice as first argument");

// Create the C++ object
QXmlStreamReader *reader = new QXmlStreamReader(device);

XmlStreamReaderPointer pointer(reader);

// store the shared pointer in the script object that we are constructing
return engine->newVariant(context->thisObject(), QVariant::fromValue(pointer));

}
Prototype functions can use qscriptvalue_cast() to cast the this object to the proper type:
Prototype函数可以使用qscriptvalue_cast强转this对象成合适的类型
QScriptValue xmlStreamReader_atEnd(QScriptContext context, QScriptEngine )
{
XmlStreamReaderPointer reader = qscriptvalue_cast”<”XmlStreamReaderPointer”>”(context->thisObject());
if (!reader)
return context->throwError(QScriptContext::TypeError, “this object is not an XmlStreamReader”);
return reader->atEnd();
}
The prototype and constructor objects are set up in the usual way:
原型和构造对象被用下面的方式设置
QScriptEngine engine;
QScriptValue xmlStreamReaderProto = engine.newObject();
xmlStreamReaderProto.setProperty(“atEnd”, engine.newFunction(xmlStreamReader_atEnd));

QScriptValue xmlStreamReaderCtor = engine.newFunction(constructXmlStreamReader, xmlStreamReaderProto);
engine.globalObject().setProperty("XmlStreamReader", xmlStreamReaderCtor);

Scripts can now construct QXmlStreamReader objects by calling the XmlStreamReader constructor, and when the Qt Script object is garbage-collected (or the script engine is destroyed), the QXmlStreamReader object is destroyed as well.
脚本可以构造QXmlStreamReader对象通过调用XmlStreamReader的构造器并且当Qt Script对象被回收时,QXmlStreamReader对象也被销毁了。
Defining Custom Script Classes with QScriptClass
用QScriptClass自定义脚本类。
There are cases where neither the dynamic QObject binding provided by QScriptEngine::newQObject() or the manual binding provided by QScriptEngine::newFunction() is sufficient. For example, you might want to implement a dynamic script proxy to an underlying object; or you might want to implement an array-like class (i.e. that gives special treatment to properties that are valid array indexes, and to the property “length”). In such cases, you can subclass QScriptClass to achieve the desired behavior.
这有些例子无论是newQObject()提供的动态绑定QObject还是newFunction()提供的手动绑定都是足够的。例如,你可能想实现一个动态脚本代理一个潜在对象;或者你可能想实现一个类似于数组的类(这给出特殊处理的数组索引是有效的属性并且length属性)。在这些情况下,你可以子类化QScriptClass实现想要的行为。
QScriptClass allows you to handle all property access for a (class of) script object through virtual get/set property functions. Iteration of custom properties is also supported through the QScriptClassPropertyIterator class; this means you can advertise properties to be reported by for-in script statements and QScriptValueIterator.
QScriptClass允许你通过虚拟的get/set属性函数处理一个脚本对象访问的所有属性。通过QScriptClassPropertyIterator类支持自定义属性的迭代。这意味着你可以通过for-in脚本语句和QScriptValueIterator访问属性。
Error Handling and Debugging Facilities
错误处理和调试功能
Syntax errors in scripts will be reported as soon as a script is evaluated; QScriptEngine::evaluate() will return a SyntaxError object that you can convert to a string to get a description of the error.
脚本一被评估脚本中的语法错误会被报告出来;evaluate()将返回一个语法错误对象,你可以转换成一个描述错误的字符串。
The QScriptEngine::uncaughtExceptionBacktrace() function gives you a human-readable backtrace of the last uncaught exception. In order to get useful filename information in backtraces, you should pass proper filenames to QScriptEngine::evaluate() when evaluating your scripts.
uncaughtExceptionBacktrace()给了你一个人可读的回溯过去未捕获的异常。为了在回溯中获得有用的文件名信息,你可以传递一个合适的文件名给evaluate()当评估你的脚本的时候。
Often an exception doesn’t happen at the time the script is evaluated, but at a later time when a function defined by the script is actually executed. For C++ signal handlers, this is tricky; consider the case where the clicked() signal of a button is connected to a script function, and that script function causes a script exception when it is handling the signal. Where is that script exception propagated to?
通常在脚本评估的时候不会发生异常,但是稍后当一个在脚本中定义的函数被执行时可能会发生。对C++信号处理来说这是棘手的。思考这种情况当一个按钮的clicked()信号被连接到一个脚本函数并且脚本函数导致了一个脚本异常当它处理信号的时候。脚本异常将会被传播到哪里呢?
The solution is to connect to the QScriptEngine::signalHandlerException() signal; this will give you notification when a signal handler causes an exception, so that you can find out what happened and/or recover from it.
解决方案是连接到signalHandlerException信号,这将给你一个通知当一个信号处理发生异常时,以便于你可以发现并且恢复。
In Qt 4.4 the QScriptEngineAgent class was introduced. QScriptEngineAgent provides an interface for reporting low-level “events” in a script engine, such as when a function is entered or when a new script statement is reached. By subclassing QScriptEngineAgent you can be notified of these events and perform some action, if you want. QScriptEngineAgent itself doesn’t provide any debugging-specific functionality (e.g. setting breakpoints), but it is the basis of tools that do.
在Qt4.4中QScriptEngineAgent被介绍。QScriptEngineAgent在脚本引擎中提供了一个低级别的事件报告接口,例如当进入一个函数或者当到达一个新的脚本语句。通过子类化QScriptEngineAgent,你可以被这些事件通知并且执行一些操作,如果你想。QScriptEngineAgent本身不提供任何特殊的调试功能但是它是做这的基础工具。
The Qt Script Tools module provides a Qt Script debugger that can be embedded into your application.
Qt Script工具模块提供一个Qt Script调试器可以内嵌到你的应用中。
Redefining print()
重定义print()
Qt Script provides a built-in print() function that can be useful for simple debugging purposes. The built-in print() function writes to standard output. You can redefine the print() function (or add your own function, e.g. debug() or log()) that redirects the text to somewhere else. The following code shows a custom print() that adds text to a QPlainTextEdit.
Qt Script提供了一个内置的print函数可以用来简单的调试输出。内置的print()函数写入标准输出。你可以重新定义print()函数(或者添加你自己的函数)重定向文本到任何其他地方。下面的代码展示了一个自定义的print()添加文本到QPlainTextEdit.
QScriptValue myPrintFunction(QScriptContext *context, QScriptEngine *engine)
{
QString result;
for (int i = 0; i < context->argumentCount(); ++i) {
if (i > 0)
result.append(” “);
result.append(context->argument(i).toString());
}

QScriptValue calleeData = context->callee().data();
QPlainTextEdit *edit = qobject_cast<QPlainTextEdit*>(calleeData.toQObject());
edit->appendPlainText(result);

return engine->undefinedValue();

}
The following code shows how the custom print() function may be initialized and used.
下面的代码展示了如何初始化和使用自定义print()函数
int main(int argc, char **argv)
{
QApplication app(argc, argv);

QScriptEngine eng;
QPlainTextEdit edit;

QScriptValue fun = eng.newFunction(myPrintFunction);
fun.setData(eng.newQObject(&edit));
eng.globalObject().setProperty("print", fun);

eng.evaluate("print('hello', 'world')");

edit.show();
return app.exec();

}
A pointer to the QPlainTextEdit is stored as an internal property of the script function itself, so that it can be retrieved when the function is called.
一个指向QPlainTextEdit的指针被作为一个脚本函数内部属性存储在函数中,以便于它可以被检索到当函数被调用的时候。
Using Qt Script Extensions
使用Qt Script扩展
The QScriptEngine::importExtension() function can be used to load plugins into a script engine. Plugins typically add some extra functionality to the engine; for example, a plugin might add full bindings for the Qt Arthur painting API, so that those classes may be used from Qt Script scripts. There are currently no script plugins shipped with Qt.
importExtension函数可以用来加载插件到一个脚本引擎。插件可以对引擎添加一些额外的功能。例如:一个插件可能添加完全绑定到Qt的Arthur绘图API,以便Qt Script脚本可以使用这些类。目前还没有脚本插件附带在Qt上。
If you are implementing some Qt Script functionality that you want other Qt application developers to be able to use, developing an extension (e.g. by subclassing QScriptExtensionPlugin) is worth looking into.
如果你想实现一些Qt Script的功能,你想Qt应用开发者也可以使用,开发一个扩展是值得考虑的。
Internationalization
国际化
Since Qt 4.5, Qt Script supports internationalization of scripts by building on the C++ internationalization functionality (see Internationalization with Qt).
从Qt4.5开始Qt Script支持脚本国际化通过构建c++国际化功能。
Use qsTr() for All Literal Text
对所有的字面文本使用qsTr()
Wherever your script uses “quoted text” for text that will be presented to the user, ensure that it is processed by the QCoreApplication::translate() function. Essentially all that is necessary to achieve this is to use the qsTr() script function. Example:
在脚本使用将要提交给用户的引号文本地方,确保它都会被translate()函数处理。基本上所有需要实现这一目标的都可以使用qsTr()脚本函数。例如:
myButton.text = qsTr(“Hello world!”);
This accounts for 99% of the user-visible strings you’re likely to write.
这认为用户可见字符串的99%,你可能会这么写。
The qsTr() function uses the basename of the script’s filename (see QFileInfo::baseName()) as the translation context; if the filename is not unique in your project, you should use the qsTranslate() function and pass a suitable context as the first argument. Example:
qsTr()函数使用了脚本的文件名的基本名作为翻译上下文。如果在你的工程里文件名不唯一,你应该使用qsTranslate函数并且传递一个合适的上下文作为第一个参数。例如:
myButton.text = qsTranslate(“MyAwesomeScript”, “Hello world!”);
If you need to have translatable text completely outside a function, there are two functions to help: QT_TR_NOOP() and QT_TRANSLATE_NOOP(). They merely mark the text for extraction by the lupdate utility described below. At runtime, these functions simply return the text to translate unmodified.
如果你需要完全在函数之外翻译文本,这有两个函数可以帮助你:QT_TR_NOOP()和QT_TRANSLATE_NOOP.它们仅仅标记要提取的文本,通过lupdate功能描述。这些函数仅仅返回未修改的翻译文本。
Example of QT_TR_NOOP():

FriendlyConversation.prototype.greeting = function(type)
{
if (FriendlyConversation[‘greeting_strings’] == undefined) {
FriendlyConversation[‘greeting_strings’] = [
QT_TR_NOOP(“Hello”),
QT_TR_NOOP(“Goodbye”)
];
}
return qsTr(FriendlyConversation.greeting_strings[type]);
}
Example of QT_TRANSLATE_NOOP():

FriendlyConversation.prototype.greeting = function(type)
{
if (FriendlyConversation[‘greeting_strings’] == undefined) {
FriendlyConversation[‘greeting_strings’] = [
QT_TRANSLATE_NOOP(“FriendlyConversation”, “Hello”),
QT_TRANSLATE_NOOP(“FriendlyConversation”, “Goodbye”)
];
}
return qsTranslate(“FriendlyConversation”, FriendlyConversation.greeting_strings[type]);
}
Use String.prototype.arg() for Dynamic Text
对动态文本使用String.prototype.arg().
The String.prototype.arg() function (which is modeled after QString::arg()) offers a simple means for substituting arguments:
String.prototype.arg()函数提供一个替代参数的简单方法。
FileCopier.prototype.showProgress = function(done, total, currentFileName)
{
this.label.text = qsTr(“%1 of %2 files copied.\nCopying: %3”)
.arg(done)
.arg(total)
.arg(currentFileName);
}
Produce Translations
产生翻译
Once you are using qsTr() and/or qsTranslate() throughout your scripts, you can start producing translations of the user-visible text in your program.
一旦你通过你的脚本在使用qsTr()或者qsTranslate(),你可以在你的程序中开始用户可见文本的翻译。
The Qt Linguist Manual provides further information about Qt’s translation tools, Qt Linguist, lupdate and lrelease.
Qt翻译家参考手册提供了关于Qt翻译工具,Qt Linguist,lupdate,lrelease更深入的信息
Translation of Qt Script scripts is a three-step process:
Qt Script脚本翻译分三步处理:
1. Run lupdate to extract translatable text from the script source code of the Qt application, resulting in a message file for translators (a TS file). The utility recognizes qsTr(), qsTranslate() and the QT_TR*_NOOP() functions described above and produces TS files (usually one per language).
运行lupdate来提取来自脚本源代码中待翻译的文本,生成一个翻译消息文件。识别上面描述的qsTr(),qsTranslate()和QT_TR*_NOOP()函数并且产生TS文件。
2.Provide translations for the source texts in the TS file, using Qt Linguist. Since TS files are in XML format, you can also edit them by hand.
在TS文件中为源文本提供翻译,使用Qt预言家.因为TS文件是XML格式,你也可以手工编辑。
3.Run lrelease to obtain a light-weight message file (a QM file) from the TS file, suitable only for end use. Think of the TS files as “source files”, and QM files as “object files”. The translator edits the TS files, but the users of your application only need the QM files. Both kinds of files are platform and locale independent.
运行lrelease从TS文件获取一个轻量的消息文件,仅仅适合最后使用。思考TS文件作为源文件并且qm作为目标文件。翻译器编辑TS文件但是你应用程序的用户仅仅需要QM文件。这两种类型的文件独立于平台和语言环境。
Typically, you will repeat these steps for every release of your application. The lupdate utility does its best to reuse the translations from previous releases.
典型地,你将重复这些步骤为你程序的每一个release。lupdate功能是尽量重用以前release的翻译。
When running lupdate, you must specify the location of the script(s), and the name of the TS file to produce. Examples:
当运行lupdate时,你必须指定脚本的位置并且生成ts文件的名字.例如:
lupdate myscript.qs -ts myscript_la.ts
will extract translatable text from myscript.qs and create the translation file myscript_la.qs.
将从myscript.qs中提取可翻译的文本并且创建翻译文件myscript_la.qs.
lupdate -extensions qs scripts/ -ts scripts_la.ts
will extract translatable text from all files ending with .qs in the scripts folder and create the translation file scripts_la.qs.
将从所有以.qs结尾的文件中提取翻译文本并且创建翻译文件scripts_la.qs.
Alternatively, you can create a separate qmake project file that sets up the SOURCES and TRANSLATIONS variables appropriately; then run lupdate with the project file as input.
同样地,你可以创建一个分离的qmake工程文件通过设置SOURCES和TRANSLATIONS变量,然后运行lupdate用工程文件作为输出。
lrelease myscript_la.ts
When running lrelease, you must specify the name of the TS input file; or, if you are using a qmake project file to manage script translations, you specify the name of that file. lrelease will create myscript_la.qm, the binary representation of the translation.
当运行lrelease时,你必须指定输入Ts文件的名字,或者如果你正在使用qmake工程文件来管理脚本翻译,你可以指定文件的名字。lrelease将创建myscript_la.qm,翻译的二进制表示。
Apply Translations
应用翻译
In your application, you must use QTranslator::load() to load the translation files appropriate for the user’s language, and install them using QCoreApplication::installTranslator(). Finally, you must call QScriptEngine::installTranslatorFunctions() to make the script translation functions (qsTr(), qsTranslate() and QT_TR*_NOOP()) available to scripts that are subsequently evaluated by QScriptEngine::evaluate(). For scripts that are using the qsTr() function, the proper filename must be passed as second argument to QScriptEngine::evaluate().
在你的应用程序中,你必须使用QTranslator::load()来为用户加载合适的翻译文件并且使用installTranslator来安装它们。最后,你必须调用installTranslatorFunctions来使得翻译函数qsTr等访问随后被evaluate()评估的脚本。对使用qsTr函数的脚本来说,本身的文件名必须作为第二个参数传递给evaluate().
linguist, lupdate and lrelease are installed in the bin subdirectory of the base directory Qt is installed into. Click Help|Manual in Qt Linguist to access the user’s manual; it contains a tutorial to get you started.
linguist, lupdate 和 lrelease被安装在Qt基础目录的子目录bin下。在Qt Linguist点击help|Manual访问用户手册。它包含一个入门教程。
See also the Hello Script Example.也可以看看hello Script例子
ECMAScript Compatibility
ECMAScript兼容性
Qt Script implements all the built-in objects and properties defined in the ECMA-262 standard; see the ECMAScript reference for an overview.
Qt Script实现的所有内置的对象和属性都被定义在ECMA-262标准中,可以看ECMAScript参考文档的概览。
Qt Script Extensions to ECMAScript
Qt Script对ECMAScript扩展。
proto
The prototype of an object (QScriptValue::prototype()) can be accessed through its proto property in script code. This property has the QScriptValue::Undeletable flag set. For example:
在脚本代码中一个对象的原型(prototype())可以通过它的proto属性来访问。这个属性有Undeletable标志位。例如:
var o = new Object();
(o.proto === Object.prototype); // this evaluates to true
Object.prototype.defineGetter
This function installs a getter function for a property of an object. The first argument is the property name, and the second is the function to call to get the value of that property. When the function is invoked, the this object will be the object whose property is accessed. For example:
这个函数为一个对象的一个属性安装一个getter函数。第一个参数是属性名,第二个参数是获取属性值的函数。当函数被调用的时候,this对象将会是属性值被访问的那个对象。例如:
var o = new Object();
o.defineGetter(“x”, function() { return 123; });
var y = o.x; // 123
Object.prototype.defineSetter
This function installs a setter function for a property of an object. The first argument is the property name, and the second is the function to call to set the value of that property. When the function is invoked, the this object will be the object whose property is accessed. For example:
这个函数为一个对象的一个属性安装了一个setter函数。第一个参数是属性名,第二个参数是设置属性值的函数.当函数被调用的时候,this对象将是属性值被访问的那个对象。例如:
var o = new Object();
o.defineSetter(“x”, function(v) { print(“and the value is:”, v); });
o.x = 123; // will print “and the value is: 123”

Function.prototype.connect
This function connects a signal to a slot. Usage of this function is described in the section Using Signals and Slots.
这个函数连接一个信号到一个槽.这个函数的用法在使用信号和槽的章节中被描述。
Function.prototype.disconnect
This function disconnects a signal from a slot. Usage of this function is described in the section Using Signals and Slots.
这个函数断开一个信号和槽的连接。这个函数的用法在使用信号和槽的章节中被描述。
QObject.prototype.findChild
This function is semantically equivalent to QObject::findChild().
这个函数跟QObject::findChild()语义相同。
QObject.prototype.findChildren
This function is semantically equivalent to QObject::findChildren().
这个函数跟QObject::findChildren()语义相同。
QObject.prototype.toString
This function returns a default string representation of a QObject.
这个函数返回代表一个对象的默认的字符串
gc
This function invokes the garbage collector.
这个函数调用垃圾回收器
Error.prototype.backtrace
This function returns a human-readable backtrace, in the form of an array of strings.
这个函数返回人类可读的回溯以一个字符串数组的形势。
Error objects have the following additional properties:
错误对象有下面额外的属性
lineNumber: The line number where the error occurred.错误发生的行号
fileName: The file name where the error occurred (if a file name was passed to QScriptEngine::evaluate()).错误发生的文件名。(如果一个文件名被传递给evaluate())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值