diff options
61 files changed, 1355 insertions, 1598 deletions
diff --git a/doc/src/declarative/qmlforcpp.qdoc b/doc/src/declarative/qmlforcpp.qdoc index f0675fe..282f261 100644 --- a/doc/src/declarative/qmlforcpp.qdoc +++ b/doc/src/declarative/qmlforcpp.qdoc @@ -1,15 +1,14 @@ /*! \page qmlforcpp.html \target qmlforcpp - \title Qt Declarative Markup Language For C++ Programmers + \title QML for C++ Programmers This page describes the QML format and how to use and extend it from C++. - The QML syntax declaratively describes in XML how to construct an in memory - object tree. QML is usually used to describe a visual scene graph - using - \l {graphicsview}{GraphicsView} or the \l {fxprimitives}{Fx Primitives} - but it is not conceptually - limited to this: the QML format is an abstract XML description of \b any - object tree. + The QML syntax declaratively describes how to construct an in memory + object tree. QML is usually used to describe a visual scene graph + but it is not conceptually limited to this: the QML format is an abstract + description of \b any object tree. QML also includes property bindings. Bindings are ECMAScript expressions of a properties value. Whenever the value of the expression changes - @@ -27,58 +26,40 @@ The following code uses the C++ interface to create 100 red rectangles based on a simple declarative component description. - \raw html - <table border="0"> - <tr> - <td> - \endraw + \code - QmlComponent redRectangle("<Rect color=\"red\" width=\"100\" height=\"100\" />"); + QmlComponent redRectangle("Rect { color: \"red\"; width: 100; height: 100 }"); for (int ii = 0; ii < 100; ++ii) { QObject *rectangle = redRectangle.create(); // ... do something with the rectangle ... } \endcode - \raw html - </td> - </tr> - </table> - \endraw - Each independent XML file describes a QML component, but it is - also possible to create sub-components within a QML file as will be - shown later. + Each independent file describes a QML component, but it is also possible to + create sub-components within a QML file as will be shown later. \section1 QML Format 101 This is some sample QML code. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code - <Image id="myRect" x="10" y="10" width="100" height="100" src="background.png"> - <Text width="100"> - <height>50</height> - <color>white</color> - <font.fontSize>16</font.fontSize> - Hello world! - </Text> - </Image> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw - - In QML, XML tags and attributes correspond to Qt objects and properties. - The general rule of thumb is any tag or attribute name that starts with a - capital letter refers to a class, and names that start with a lower case - letter to properties. It is not possible to access a property that starts - with a capital letter from QML. + Image { + id: myRect + x: 10 + y: 10 + width: 100 + height: 100 + src: "background.png" + + Text { + height: 50 + width: 100 + color: "white" + font.fontSize: 16 + text: "Hello world!" + } + } + \endcode The QML snippet shown above instantiates one \c Image instance and one \c Text instance and sets properties on both. \b Everything in QML @@ -86,50 +67,18 @@ assigning a property a value. QML relies heavily on Qt's meta object system and can only instantiate classes that derive from QObject. - Setting properties can be done in two ways: as an XML attribute directly on - the class tag that created the the object, or as sub-tags. - Although syntactically different, their behaviour is identical. The two QML - snippets below behave exactly the same. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw - \code - <Rect x="10" y="10" /> - \endcode -\raw HTML - </td> - <td> -\endraw - \code - <Rect> - <x>10</x> - <y>10</y> - </Rect> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw - Arbitrary mixing and matching between the two is allowed. - QML can set properties that are more complex than just simple types like - integers and strings. Properties can be object pointers or Qt interface pointers - or even lists of object or Qt interface pointers! QML is typesafe, and will - ensure that only the valid types are assigned to properties. + integers and strings. Properties can be object pointers or Qt interface + pointers or even lists of object or Qt interface pointers! QML is typesafe, + and will ensure that only the valid types are assigned to properties. Assigning an object to a property is as simple as assigning a basic integer. Attempting to assign an object to a property when type coercian fails will produce an error. The following shows an example of valid and of invalid QML and the corresponding C++ classes. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw + \table + \row \o \code class Image : public QObject { @@ -142,86 +91,33 @@ ... }; \endcode -\raw HTML - </td> - <td> -\endraw - \code - <!-- OK --> - <Image> - <filter> - <ImageFilter /> - </filter> - </Image> - - <!-- NOT OK: Image cannot be cast into ImageFilter --> - <Image> - <filter> - <Image /> - </filter> - </Image> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + \o \code + // OK + Image { + filter: ImageFilter {} + } - Classes can also define an optional default property. The default property - is used for assignment if no explicit property has been specified. - In the example below, the string "Hello World!" will be assigned to - the \c Text element's default property - which happens to be the \c text - property. Both lines do the same thing, one explicitly and one implicitly. - -\raw HTML - <table border="0"> - <tr> - <td> -\endraw - \code - <Text text="Hello World!" /> - <Text>Hello World!</Text> - \endcode -\raw HTML - </td> - <td> -\endraw - \code - class Text : public QObject - { - ... - Q_PROPERTY(QString text READ text WRITE setText) - Q_CLASSINFO("DefaultProperty", "text") - }; + // NOT OK: Image cannot be cast into ImageFilter + Image { + filter: Image {} + } \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + \endtable + Classes can also define an optional default property. The default property + is used for assignment if no explicit property has been specified. Any object property can be the default, even complex properties like lists of objects. The default property of the \c Rect class is the \c children property, a list of \c Item's. In the following example, as both \c Image and \c Text inherit from \c Item the \c Image and \c Text instances are added to the parent's \c children property. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code - <Rect> - <Image /> - <Text /> - </Rect> + Rect { + Image {} + Text {} + } \endcode -\raw HTML - </td> - </tr> - </table> -\endraw Properties that return read-only object pointers can be used recursively. This can be used, for example, to group properties together. The @@ -230,11 +126,8 @@ QML makes it easy to interact with these grouped properties, as the following shows - everything you would expect to work, just does. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw + \table + \row \o \code class Text : public ... { @@ -250,67 +143,36 @@ Q_PROPERTY(int size READ size WRITE setSize); }; \endcode -\raw HTML - </td> - <td> -\endraw + \o \code - <Text font.family="helvetica"> - <font> - <bold>true</bold> - <italic>true</italic> - </font> - <font.size>12</font.size> - </Text> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + Text { + font.family: "helvetica" + font.size: 12 + font { + bold: true + italic: true + } + } + \endcode + \endtable \section1 Defining QML Types The QML engine has no intrinsic knowledge of any class types. Instead the programmer must define the C++ types, and their corresponding QML - name. There are three ways of adding known types to the QML engine: - \list - \o + name. + \code #define QML_DECLARE_TYPE(T) #define QML_DEFINE_TYPE(T,QmlName) \endcode + Adding these macros to your library or executable automatically makes the C++ type \a T available from the declarative markup language under the name \a QmlName. Of course there's nothing stopping you using the same - name for both the C++ and the QML name!<br> - Most types are added to the QML engine using these macros. The only - requirement is that \a T inherits QObject and has a default constructor. - \o - \code - #define QML_DEFINE_CUSTOM_PARSER(QmlName, CustomParserClass) - \endcode - Custom parsers define a way to translate between declarative XML and an - object instance in the case the default object model lets you down. Free - form lists (\c {<ListModel>} are an example of a custom parser. - Custom parsers implement the \l QmlCustomParser interface. - - Custom parsers give a developer very fine grain control over how a type is - instantiated from the XML that describes it. During the - compilation phase, the custom parser is presented with the XML via a - QXmlStreamReader and must - compile this down into an opaque blob that is returned to the compiler. - When, at runtime, the type is instantiated, the opaque blob is passed into - the custom parser, which must return a QObject derived type. - - \o QML::ClassFactory - - The QML engine calls the class factory as a last resort when trying to - create a type. The class factory returns a \l QmlComponent instance for - the type if it can create it. This allows "on the fly" types to be created. - For example, a class factory is used to support automatic instantiation of - .qml template files. - \endlist + name for both the C++ and the QML name! + Any type can be added to the QML engine using these macros. The only + requirements are that \a T inherits QObject and that it has a default constructor. \section1 Property Binding @@ -321,31 +183,32 @@ Property bindings are ECMAScript expressions and can be applied to any object property. C++ classes don't have to do anything special to get - binding support other than define appropriate properties. Property binding - expressions are differentiated from regular constant literals by surrounding - them in braces. + binding support other than define appropriate properties. When a non-literal + property assignment appears in a QML file, it is automatically treated as a + property binding. Here's a simple example that stacks a red, blue and green rectangle. Bindings are used to ensure that the height of each is kept equal to it's parent's. Were the root rectangle's height property to change, the child rectangles height would be updated automatically. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw + \code - <Rect color="red" width="100"> - <Rect color="blue" width="50" height="{parent.height}"> - <Rect color="green" width="25" height="{parent.height}"> - </Rect> - </Rect> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + Rect { + color: "red" + width: 100 + Rect { + color: "blue" + width: 50 + height: parent.height + Rect { + color: "green" + width: 25 + height: parent.height + } + } + } + \endcode + Binding expressions execute in a context. A context behaves as a scope and defines how the expression resolves property and variable names. Although the two expressions in the last example are the same, the value of \c parent @@ -371,24 +234,14 @@ the case of grouped properties - the object context is that of the instantiated object, the consequences of which are shown below. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code - <!-- OK --> <!-- NOT OK: Text has no italic property --> - <Text> <Text> - <font> <font> - <bold>{font.italic}</bold> <bold>{italic}</bold> - </font> </font> - </Text> </Text> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + // OK // NOT OK + Text { Text { + font { font { + bold: font.italic bold: italic + } } + } } + \endcode The second context is the "component context". Each QML component (and consequently each QML file) is created in its own unique binding context. @@ -396,21 +249,14 @@ object - but in this case it is the component's root object. An example will illustrate best - the resultant text will read "background.png". -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code - <Image src="background.png"> - <Text text="{src}" /> - </Image> + Image { + src: "background.png" + Text { + text: src + } + } \endcode -\raw HTML - </td> - </tr> - </table> -\endraw If the name is not found in either of these contexts, the context heirarchy is searched parent-by-parent until the name is either found, or the @@ -421,23 +267,22 @@ parent, rather than fixing them all to a single common point. Here's the example rewritten to do just that. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code - <Rect color="red" width="100"> - <Rect color="blue" width="50" height="{parent.height}"> - <Rect color="green" width="25" height="{parent.parent.height}"> - </Rect> - </Rect> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + Rect { + color: "red" + width: 100 + Rect { + color: "blue" + width: 50 + height: parent.height + Rect { + color: "green" + width: 25 + height: parent.parent.height + } + } + } + \endcode Clearly this sort of fragile relationship is undesirable and unmanageable - moving the green rectangle to be a sibling of the blue or introducing a @@ -450,28 +295,26 @@ property. Every object automatically has this magical property (if the object also has an actual property called \c id, that gets set too). As an id allows an object to be referenced directly, it must be unique within - a component. Any number of id's can exist, but they must all begin with - a capital letter. An id of "Root" is valid, while an id of "root" is not. - \note This is not technically true - lowercase id names do work, but are - slower. Support will probably be removed for them eventually. - -\raw HTML - <table border="0"> - <tr> - <td> -\endraw - \code - <Rect id="Root" color="red" width="{GreenRect.width + 75}"> - <Rect color="blue" width="{GreenRect.width + 25}" height="{Root.height}"> - <Rect id="GreenRect" color="green" width="25" height="{Root.height}"> - </Rect> - </Rect> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + a component. By convention, id's should start with an uppercase letter. + + \code + Rect { + id: Root + color: "red" + width: GreenRect.width + 75 + height: Root.height + Rect { + color: "blue" + width: GreenRect.width + 25 + Rect { + id: GreenRect + color: "green" + width: 25 + height: Root.height + } + } + } + \endcode To relate id's back to QmlBindContext, id's exist as properties on the component context. @@ -483,11 +326,6 @@ the expression will not be updated if the value changes. The following is an example of a QML friendly property declaration. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code class Example : public QObject { @@ -500,11 +338,6 @@ void sampleChanged(int); }; \endcode -\raw HTML - </td> - </tr> - </table> -\endraw While generally no changes are needed to a C++ class to use property binding, sometimes more advanced interaction between the binding engine and @@ -523,19 +356,12 @@ easily associate ECMAScript with signals. Consider the following example, in which Button is a made-up type with a clicked() signal. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code - <Button text="Hello world!" onClicked="print(text)" /> + Button { + text: "Hello world!" + onClicked: print(text) + } \endcode -\raw HTML - </td> - </tr> - </table> -\endraw Clicking on the button causes "Hello world!" to be printed to the console (or lost forever if you're running Windows). @@ -558,23 +384,15 @@ below, as long as you remember to name the parameters of your signal in C++ (see QMetaMethod::parameterNames()). -\raw HTML - <table border="0"> - <tr> - <td> -\endraw + \table + \row \o \code - <Example> - <onDoSomething> - for(var ii = 0; ii < count; ++ii) - print(message) - </onDoSomething> - </Example> - \endcode -\raw HTML - </td> - <td> -\endraw + Example { + onDoSomething: for(var ii = 0; ii < count; ++ii) + print(message) + } + \endcode + \o \code class Example : public QObject { @@ -583,11 +401,7 @@ void doSomething(int count, const QString &message); }; \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + \endtable Just like property bindings, signal scripts are executed in a context. The signal script context is identical in scope to the "object context" under @@ -599,41 +413,23 @@ default method is defined just like a default property, though the special "DefaultMethod" class info. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code Q_CLASSINFO("DefaultMethod", "myMethod(int)"); \endcode -\raw HTML - </td> - </tr> - </table> -\endraw This is useful in achieving several use cases, like that below which moves the button when it is clicked. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code - <Button id="MyButton"> - <onClicked> - <NumericAnimation target="{MyButton}" property="x" to="100" /> - </onClicked> - </Button> + Button { + id: MyButton + onClicked: NumericAnimation { + target: MyButton + property: "x" + to: 100 + } + } \endcode -\raw HTML - </td> - </tr> - </table> -\endraw - If the class itself actually defines a property called "on<Name>", this will be assigned the string value and the signal handling behaviour will be @@ -648,65 +444,44 @@ Qt's QGridLayout is one such example. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code - <QGridLayout> - <QLabel QGridLayout.row="0" QGridLayout.column="0" text="Name:"/> - <QLineEdit QGridLayout.row="0" QGridLayout.column="1" /> - - <QLabel QGridLayout.row="1" QGridLayout.column="0" text="Occupation:"/> - <QLineEdit QGridLayout.row="1" QGridLayout.column="1" /> - </QGridLayout> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + QGridLayout { + QLabel { + QGridLayout.row: 0 + QGridLayout.column: 0 + text: "Name:" + } + QLineEdit { + QGridLayout.row: 0 + QGridLayout.column: 1 + } + + QLabel { + QGridLayout.row: 1 + QGridLayout.column: 0 + text: "Occupation:" + } + QLineEdit { + QGridLayout.row: 1 + QGridLayout.column: 1 + } + } + \endcode - Attached properties are identified by the use of a class name, in the + Attached properties are identified by the use of a type name, in the case shown \c QGridLayout, as a grouped property specifier. To prevent ambiguity with actual class instantiations, attached properties must always be specified to include a period but can otherwise be used just like regular properties. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw - \code - <!-- OK --> <!-- NOT OK: Creates a QGridLayout, rather than assigning attached property --> - <QLabel> <QLabel> - <QGridLayout.row>0</QGridLayout.row> <QGridLayout> - </QLabel> <row>0</row> - </QGridLayout> - </QLabel> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw - C++ types provide attached properties by declaring the public function \c qmlAttachedProperties like this example. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw + \table + \row \o \code static QObject *Type::qmlAttachedProperties(QObject *); \endcode -\raw HTML - </td> - <td> -\endraw + \o \code class Example : public QObject { @@ -715,18 +490,14 @@ static QObject *qmlAttachedProperties(QObject *); }; \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + \endtable When an attached property is accessed, the QML engine will call this method to create an attachment object, passing in the object instance that the attached property applies to. The attachment object should define all the attached properties, and is generally parented to the provided object - instance to avoid memory leaks. The QML engine does not save this object, - so it is necessary for the attached property function to ensure that + instance to avoid memory leaks. The QML engine does not saves this object, + so it is not necessary for the attached property function to ensure that multiple calls for the same instance object return the same attached object. While conceptually simple, implementing an attachment object is not quite @@ -737,23 +508,15 @@ that \b any object can attach \b any attached property. The following is perfectly valid, although the attached property has no actual effect: -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code - <FancyGridLayout> - <Item> - <Button QGridLayout.row="1" /> - </Item> - </FancyGridLayout> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + FancyGridLayout { + Item { + Button { + QGridLayout.row: 1 + } + } + } + \endcode The property has no effect because the (made-up) FancyGridLayout type defines the meaning of the \c row attached property only to apply to its direct children. It @@ -769,29 +532,17 @@ \section1 Property Value Sources Intrinsically, the QML engine can assign a property either a static value, - such as a number of object tree, or a property binding. It is possible for + such as a number or an object tree, or a property binding. It is possible for advanced users to extend the engine to assign other "types" of values to properties. These "types" are known as property value sources. - Consider the following \l {fxprimitives}{Fx Primitives} example. + Consider the following example. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code - <Rect width="100" height="100" color="red"> - <x> - <NumericAnimation running="true" repeat="true" from="0" to="100" /> - </x> - </Rect> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + Rect { + x: NumericAnimation { running: true; repeat; true; from: 0; to: 100; } + } + \endcode Here the \c x property of the rectangle will be animated from 0 to 100. To support this, the NumericAnimation class inherits the @@ -805,26 +556,17 @@ QML is designed to allow you to build fully working types without writing a line of C++ code. This is, for example, used extensively when designing - applications using the \l {fxprimitives}{Fx Primitives}. To create new types, it is + applications using the Fluid UI primitives. To create new types, it is necessary to be able to define new signals, slots and properties in QML. - \note slots are not yet supported - - Any object is extensible in this way under QML, using the special - \c properties and \c signals properties. Like \c id, these two properties - are automatically available on all types under QML and accessible from - other QML files or directly from C++. - In this example, a Button is extended to have an additional "text2" property (which always returns "Hello world!") and an additional signal "clicked2" that is also emitted when the button is clicked. Not a very useful extension, but an extension nonetheless. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw + \table + \row + \o \code QmlComponent component(xmlData); QObject *object = component.create(); @@ -833,44 +575,36 @@ // Will be emitted whenever the button is clicked QObject::connect(object, SIGNAL(clicked2()), this, SLOT(...)); \endcode -\raw HTML - </td> - <td> -\endraw + \o \code - <Button text="Hello!"> - <properties> - <Property name="text2" type="string" /> - </properties> - <signals> - <Signal name="clicked2" /> - </signals> - <text2>Hello world!</text2> - <onClicked>clicked2.emit()</onClicked> - </Button> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw - - Any number of properties and signals can be added to an existing type. The - \c Property and \c Signal elements have the following properties that can - be set: - \table - \header \o Tag \o Property \o Description - \row \o Property \o name \o The name of the property - \row \o Property \o type \o The type of the property. The available types are: \list \o int \o bool \o double \o real \o string \o color \o date \o variant \endlist The default is variant. - \row \o Property \o value \o The initial value of the property. Setting this is just a shortcut for setting the property normally, as shown in the example above. - \row \o Property \o onValueChanged \o A special signal property that is emitted each time the property value changes. - \row \o Property \o default \o Set this as the object's default property - \row \o Signal \o name \o The name of the signal. + Button { + property string text2 + signal clicked2 + + text: "Hello!" + text2: "Hello world!" + onClicked: clicked2.emit() + } + \endcode \endtable - If the type itself actually defines a property called \c properties or - \c signals, the respective extension will be disabled for that type and - the types own properties will be set. + The general syntax for defining new properties and signals is: + + \list + \o + \code + [default] property <type> <name> [: <default value>] + \endcode + + Where type can be one of \e int, \e bool, \e double, \e real, \e string, + \e color, \e date, \e var or \e variant. + + \o + \code + signal <name> + \endcode + Currently only parameterless signals are supported. + \endlist \section1 Parser Status @@ -890,11 +624,6 @@ these notifications, all a class has to do is to inherit the interface, and notify the Qt meta system using the Q_INTERFACES() macro. For example, -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code class Example : public QObject, public QmlParserStatus { @@ -907,11 +636,6 @@ } }; \endcode -\raw HTML - </td> - </tr> - </table> -\endraw \section1 Extended Type Definitions @@ -935,29 +659,17 @@ property or slots on the extension object is used instead. When an extended type is installed, the -\raw HTML - <table border="0"> - <tr> - <td> -\endraw \code #define QML_DEFINE_EXTENDED_TYPE(T,QmlName,ExtendedTypeName) \endcode -\raw HTML - </td> - </tr> - </table> -\endraw macro should be used instead of the regular \c QML_DEFINE_TYPE. This example shows the addition of a read-only \c textLength property to QLabel being implemented as an extension. -\raw HTML - <table border="0"> - <tr> - <td> -\endraw + \table + \row + \o \code class QLabelExtension : public QObject { @@ -971,19 +683,17 @@ }; QML_DEFINE_EXTENDED_TYPE(QLabel,QLabel,QLabelExtension); \endcode -\raw HTML - </td> - <td> -\endraw + \o \code - <QLabel id="Label1" text="Hello World!" /> - <QLabel text="{'Label1 text length:' + Label1.textLength}" /> - \endcode -\raw HTML - </td> - </tr> - </table> -\endraw + QLabel { + id: Label1 + text: "Hello World!" + } + QLabel { + text: "Label1 text length: " + Label1.textLength + } + \endcode + \endtable Attributes defined through extensions are inherited, just like attributes defined on a normal class. Any types that inherit from \c QLabel, will diff --git a/doc/src/declarative/qtdeclarative.qdoc b/doc/src/declarative/qtdeclarative.qdoc index 666c8ae..67605dc 100644 --- a/doc/src/declarative/qtdeclarative.qdoc +++ b/doc/src/declarative/qtdeclarative.qdoc @@ -65,7 +65,7 @@ \o \l {qmlexamples}{Examples} \o \l {tutorial}{Tutorial: 'Hello World'} \o \l {tutorials-declarative-contacts.html}{Tutorial: 'Introduction to QML'} - \o \l {qmlforcpp}{Qt Declarative Markup Language For C++ Programmers} + \o \l {qmlforcpp}{QML For C++ Programmers} \endlist Core Features: diff --git a/doc/src/declarative/scenegraph.qdoc b/doc/src/declarative/scenegraph.qdoc deleted file mode 100644 index 2340324..0000000 --- a/doc/src/declarative/scenegraph.qdoc +++ /dev/null @@ -1,13 +0,0 @@ -/*! - \page graphicsview.html - \target graphicsview - \title GraphicsView - -*/ - -/*! - \page fxprimitives.html - \target fxprimitives - \title FX Primitives - -*/ diff --git a/doc/src/images/declarative-reuse-1.png b/doc/src/images/declarative-reuse-1.png Binary files differnew file mode 100644 index 0000000..c704457 --- /dev/null +++ b/doc/src/images/declarative-reuse-1.png diff --git a/doc/src/images/declarative-reuse-2.png b/doc/src/images/declarative-reuse-2.png Binary files differnew file mode 100644 index 0000000..0b6006b --- /dev/null +++ b/doc/src/images/declarative-reuse-2.png diff --git a/doc/src/images/declarative-reuse-3.png b/doc/src/images/declarative-reuse-3.png Binary files differnew file mode 100644 index 0000000..695a725 --- /dev/null +++ b/doc/src/images/declarative-reuse-3.png diff --git a/doc/src/images/declarative-reuse-bluerect.png b/doc/src/images/declarative-reuse-bluerect.png Binary files differnew file mode 100644 index 0000000..97dbb5f --- /dev/null +++ b/doc/src/images/declarative-reuse-bluerect.png diff --git a/doc/src/images/declarative-reuse-focus.png b/doc/src/images/declarative-reuse-focus.png Binary files differnew file mode 100644 index 0000000..f91d374 --- /dev/null +++ b/doc/src/images/declarative-reuse-focus.png diff --git a/doc/src/tutorials/declarative.qdoc b/doc/src/tutorials/declarative.qdoc index bde71da..9b9c90f 100644 --- a/doc/src/tutorials/declarative.qdoc +++ b/doc/src/tutorials/declarative.qdoc @@ -97,10 +97,7 @@ \tableofcontents The first part of this tutorial covers basic drawing of elements on the - screen and causing them to animate. The file 1_Drawing_and_Animation.qml - loads and displays each of the five stages of this tutorial in a single - window. For now you don't need to worry about the contents of - 1_Drawing_and_Animation.qml. + screen and causing them to animate. \section1 Drawing @@ -115,7 +112,9 @@ Because Declarative UI is declarative, you don't pass instructions on what to paint in a sequential manner as you may be used to. Instead elements and how they appear on the screen are declared in much the - same was as elements on a web page are declared. + same was as elements on a web page are declared. This is done using + the Qt Markup Language which we will refer to by the abbreviation QML + for the remainder of the tutorial. We will start by drawing a simple red rectangle with rounded corners. @@ -123,14 +122,11 @@ \snippet declarative/tutorials/contacts/1_Drawing_and_Animation/1/RemoveButton.qml 0 - This is the simplest of QML components. It describes a rectangle with + This is one of the simplest of QML components. It describes a rectangle with some simple properties. In QML all components start with a capital - letter, and their properties with lower case letters. Properties - can either be declared as XML attributes or as children of the - component element. + letter, and their properties with lower case letters. - The rectangle component is one of the more simple QML components. Apart - from the properties all QML components share, it has the properties + Apart from the properties all QML components share, the \l{qml-rect}{Rect} component has the properties \list \o color - The background color of the rectangle @@ -140,13 +136,9 @@ \o radius - The corner radius used to draw rounded rectangles. \endlist - \omit - For more information on the Rect element, see: TODO - \endomit - - There are also a number of properties all QML components share. To see - a full description of the base QML item, see {QFxItem}. The rectangle - drawn in the above code uses the properties; + There are also a number of properties all QML components shares, described + in the \l{qml-item}{Item} element reference documentation. The rectangle drawn in the + above code uses the properties; \list \o id - An identifier of the component @@ -154,61 +146,61 @@ \o height - the height of the component when drawn \endlist - All items have properties to handle their position on the screen, size, - clipping, rotation, scale and layout in regards to other elements. In - the current example width and height refer to how large to draw the - rectangle. The identifier allows other components to refer to the - identified component. - - Another important property of a component is its children. All components - have a list of children. When drawing, first any components earlier - siblings are drawn, then the component, then any of the components children. + Currently we have described a rectangle with a width and height of 30 pixels, filled in with + the color red and with rounded corners using a radius of 5. \section1 Layout - The next step of the tutorial adds an image over the rectangle. + The next step of the tutorial adds an image over the rectangle. We + will do this by adding an \l{qml-image}{Image} component as a child of the + \l{qml-rect}{Rect} component. All QML components have a list of children which + are drawn in order after the parent component has been drawn. + By having the \l{qml-image}{Image} + component as a child of the \l{qml-rect}{Rect} component we ensure it is drawn + over the \l{qml-rect}{Rect} component. Children also are affected by the opacity + of the parent component and calculate their position in within the bounds of + the parent component. \image declarative-removebutton-close.png \snippet declarative/tutorials/contacts/1_Drawing_and_Animation/2/RemoveButton.qml 0 The trashIcon image is added as a child of the Rectangle. In this case - the <children> tag isn't used because the default property of the - Rect component is its children. Some elements don't often have children - and use some other default component, when this is the case its possible + the children property isn't explicitly used because the default property + of the \l{qml-rect}{Rect} component is its children. Some elements often don't have children + and use some other default component. When this is the case its possible to explicitly list the sub component as a child as follows: \snippet declarative/tutorials/contacts/1_Drawing_and_Animation/2a/RemoveButton.qml 0 - The Image element allows loading an image file for display. The source + The \l{qml-image}{Image} element allows loading an image file for display. The source specified is a URL, and in this case refers to a portable network graphics file in a relative directory to where the QML file was loaded from. Also new in this code is the use of anchors. In QML components can either have their position and size specified explicitly using x, y, width and height, or they can instead specify the size and position in relation - to elements either parent or sibling elements. The Image component uses + to either parent or sibling elements. The \l{qml-image}{Image} component uses a combination of both styles. It has a fixed size, but specifies its position to align to the right of its parent and for its vertical center - to align with the vertical center of its parent. The braces "{}" are - used to indicate that the value is not a static value, but instead a - binding to an expression. In this case it binds to the parent - element, which is a special identifier that always refers to the - parent component of a component. The removeButton identifier can - be used interchangeably with parent in this case, however it must - always be a parent or sibling. Because of this its most common to - use the parent identifier as it makes later refactoring of code easier. + to align with the vertical center of its parent. Setting a property + by the identifier of a separate property binds them. This means + that if while running the example the position of the \l{qml-rect}{Rect} component's + vertical center changed, so to would the vertical center of + the \l{qml-image}{Image} component. - Anchors are most useful when the size of items might change based on - the component state or contents. + The parent value is a special identifier that always refers to the + parent component of a component. - \omit - See TODO for full list of anchor properties. - \endomit + Anchors are most useful when the size of items might change based on + the component state or contents. However they are limited in that they + must always refer to a parent or sibling component. See + \l{anchor-layout}{Anchor-based Layout} for more information on using + anchors in QML. At this point the initial state of the RemoveButton is complete. A small - rounded rectangle with a trash icon. The component also needs a - description of its open state: + rounded rectangle with a trash icon. Next we will design the open + state for the button. \image declarative-removebutton-open.png @@ -217,32 +209,31 @@ \snippet declarative/tutorials/contacts/1_Drawing_and_Animation/3/RemoveButton.qml 0 - The rectangle with is now wider by 200 pixels. Also the trashIcon has - been replaced with the confirm state children. Normally we wouldn't + The rectangle width is now wider by 200 pixels. Also the trashIcon has + been replaced. Normally we wouldn't remove the trashIcon when developing an alternate state of the RemoveButton, however since this is a tutorial its been done so that its easier to understand the alternate state we are aiming for and how it relates to transitioning between states. - We also introduce the Text element, which is used to display read only - text. \omit see {Text} for more information on the text element \endomit - Because we want text to fill the space between the icons, rather than - a fixed with the left and right anchors are specified instead. This + We also introduce the \l{qml-text}{Text} element. + Left and Right anchors are specified in terms of the neighboring icons + because we want text to fill the space between the icons. This means as the parent removeButton gets wider, so will the text component. It also means that if we animate a width change on the removeButton, - any bindings, that is the values specified by a braced expression such as - "{parent.left}" will be evaluated and animated as well. + any bindings, that is the values specified by an expression such as + \c{parent.left} will be evaluated and animated as well. \section1 Defining States When designing a component with multiple states, it should be developed - with the initial state and the changes that would be made specified - as an additional state. Its not possible to add new children to an - element when changing state, only changing the properties of existing - children. This means that all possible child components should be included + in the initial state and the changes that would be made specified + as an additional state. Its not normally possible to add new children + to an element when changing state + This means that all possible child components should be included in the initial state, and those that should not be visible in the initial state should have their opacity set to zero. Thus - for the RemoveButton we specify the starting size of the removeButton + for the RemoveButton we specify the starting size of the RemoveButton and hide any items that should not initially be visible. The code snippet below shows what the start of the duel state specification @@ -305,9 +296,9 @@ all the children of the earlier sibling, should they overlap. When a component has a signal, such as clicked, the action for the signal - can be specified using on<SignalName>, as is done above. In this + can be specified using \c{onSignalName}, as is done above. In this case when the clicked signal is emitted by the MouseRegion component, - a function called toggle() is called. It might also have been written + a function called \c{toggle()} is called. It might also have been written \code onClicked: { removeButton.state='opened' } @@ -317,14 +308,21 @@ mouse regions to use the same functionality, and also makes it easier to specify complex behavior in response to a signal. - The toggle() function is a new function specified as part of the remove + An alternative would be to explicitly state the connection: + + \snippet declarative/tutorials/contacts/1_Drawing_and_Animation/4a/RemoveButton.qml mouse region + + This will connect to the \c{clicked()} signal of the trashMouseRegion component + and execute the associated script. + + The \c{toggle()} function is a new function specified as part of the remove button element. \snippet declarative/tutorials/contacts/1_Drawing_and_Animation/4/RemoveButton.qml script Any QML component can have a set of resources specified. One of those resources is any Script that might be needed. See the - {QtScript Module}{QtScript Module} for more information on how to write + \l{qtscript}{QtScript Module} for more information on how to write script code in Qt. It is possible to refer to identified QML components @@ -333,7 +331,7 @@ \section1 Animation - Currently the RemoveButton is function, but snaps between our two states. + Currently the RemoveButton is functional, but snaps between our two states. Fortunately making the transition between states smooth is very simple. We only need one more bit of code at the end of our removeButton component. @@ -368,6 +366,8 @@ editing a field of our contact. This ContactField in turn is intended to be used in a contact editing control. + \image declarative-reuse-3.png + \section1 Loading QML Components Reusing the RemoveButton itself is very simple. When parsing a QML file @@ -386,50 +386,88 @@ \o The run directory + "/qml" \o the directory of the QML code file \o the directory of the QML code file + "/qml" - \endlist. + \endlist All the properties of the button are accessible and can be overridden from defaults. The loaded component can also refer to elements further up in the tree, so that code within - RemoveButton.qml could refer to the contactField component. However only - properties of the top level element in RemoveButton.qml are visible to - the contact field. In order to allow contact field to modify how wide - the remove button will be when opened we need to add a property to the - remove button. + RemoveButton.qml could refer to the contactField component. + Only properties of the top level element in RemoveButton.qml are visible to + the contact field. + + There are also two other ways to reuse components in QML. A component + can be reused from within the same QML file using Component and ComponentInstance + elements. The next code snippet produces three red rounded rectangles + within a large blue rectangle. + + \image declarative-reuse-bluerect.png + + \snippet declarative/tutorials/contacts/2_Reuse/1b/BlueRect.qml all + + This can be useful when the component is not complex enough to justify its + own file. The third way to reuse components allows for delaying loading + of the QML until some later event. Each \l{qml-item}{Item} includes + a special child, qmlItem, which has its definition provided by the + contents of the qml property of its parent. + + \snippet declarative/tutorials/contacts/2_Reuse/1a/ContactField.qml load + + This last method is useful if the contents of a item need to change at + run time or if the initial complexity of the loaded QML needs to be + reduced in order to improve the time it takes to start the application. In + chapter three this method is used to improve performance of + scrolling through very large numbers of items. + + Because of its simplicity, the first method is the recommended in most + cases and will be the focus of the remainder of this chapter. \section1 Properties and Signals + The next task is to be able to control aspects of the RemoveButton from + the components that use it. In particular controlling how far it + expands and how it reacts when the user clicks on the confirm icon + of the remove button. When reusing a component in a separate QML file + only the attributes of the root element are visible. To allow controlling + attributes of child elements within an imported component we need to define + some properties and signals for the RemoveButton. + \snippet declarative/tutorials/contacts/2_Reuse/2/RemoveButton.qml define properties and signals - These properties and signals are accessed from the contact field the same - way standard system components are accessed. + The children of the remove button can use these properties and signals. The + opened state can now bind the expanded width to the expandedWidth property. + + \snippet declarative/tutorials/contacts/2_Reuse/2/RemoveButton.qml use width + + Also when the confirm icon is clicked, as well as toggling the state it will + emit the confirmed signal of the RemoveButton component. + + \snippet declarative/tutorials/contacts/2_Reuse/2/RemoveButton.qml use signal + + These properties and signals can also be accessed from the contact field the same + way standard system component properties and signals are accessed. \snippet declarative/tutorials/contacts/2_Reuse/2/ContactField.qml use properties and signals Now when the remove button is expanded, it will expand to the width of the contact field. Also when the user confirms the remove action, the - text section of the contact field will be cleared. When creating a - component that does have children out of its own - bounds its important to consider whether the item should be clipped, - which is done above with \c{clip: true}. + text section of the contact field will be cleared. \section1 States Its also possible to access the state of included components. The FieldText component we will use in this tutorial is also been written specifically - for our contacts application, as was the RemoveButton component. In + for our contacts application. In this case we want it to expand when editing. One way to do this would be to anchor the field text component to the center of its parent and then let its own width change push the remove button away, however that would make it difficult to have the remove button also push the field - text to the left when the remove button expands. - - So instead we will anchor the right edge of the field text to - the left edge of the remove button and use a state change in the - contact field itself to move the remove button and the field icon out of + text to the left when the remove button expands. Instead we will anchor + the right edge of the field text to the left edge of the remove button + and use a state change in the contact field itself to move the + remove button and the field icon out of view. - \snippet declarative/tutorials/contacts/2_Reuse/3/RemoveButton.qml all + \snippet declarative/tutorials/contacts/2_Reuse/3/ContactField.qml all Apart from accessing the fieldText.state, the above code also uses the when attribute of its own editingText state. This is an alternative to using @@ -440,61 +478,63 @@ \snippet declarative/tutorials/contacts/2_Reuse/3/FieldText.qml behavior - fieldText is the enclosing component and textEdit is a TextEdit element + \c{fieldText} is the enclosing component and \c{textEdit} is a TextEdit element provided by Qt. In the QML code above, the opacity of the textLabel is - only 1 if there is text for the textEdit is empty. This is a form of + only 1 if the text for the textEdit is empty. This is a form of short cut to using states for an element, useful if only one property is changing as it is for the textLabel. To animate a property change is similar to animating a state change. Using the Behavior element we can specify how the property changes if it does change state, allowing for a smooth transition. - The fieldText element also handles changes to the text using the - onValueChanged attribute when specifying properties. - - \snippet declarative/tutorials/contacts/2_Reuse/3/FieldText.qml value change - - Because the user needs to be able to edit text in the text edit, it - shouldn't be simply bound to the text property of the FieldText component. - However if a component using the FieldText component sets the text - property of the FieldText component it should in turn set the text - of the text edit. - \section1 Key and Mouse Focus - Unlike in Qt setting focus to true on a component does not always mean + Setting focus to true on a component does not always mean that the component has focus. This is due to the declarative nature of QML, and can be affected by multiple components both indicating focus to be true. At the time of writing this tutorial both key and mouse focus handling are still being improved. Hence we will only lightly cover the topic. - Normally in QML this is handled by FocusRealm components. A focus realm - is a sort of cut off point for determining focus. If a FocusRealm does - not have focus then any children of it won't be able to get focus even - if they do set focus to true. If your component has multiple child - components that could gain focus ensure that they are guarded by FocusRealm - component, and add code to handle which focus realms have focus - at that level. The alternative and approach done at this stage in - the tutorial is to only have one component set focus to true at a time. + For an item to have key focus in QML it is required that: + + \list + \o If there is a FocusRealm ancestor of the component that it has focus as well. + \o That it is the most recent component within the focus realms descendent's + to receive focus + \endlist + + The read-only property activeFocus can be used to determine whether a + component will receive key input. Any un-handled keys will be passed to + the components parent, which in turn will pass keys it doesn't handle up to its + own ancestors. + + Some components such as ListView components are also FocusRealm components, as they + handle focus among the child list items. + + At this stage of the tutorial it is sufficient to use the setting of 'focus' + as we only have a list of line edits and only one should be active at any given time. Currently if multiple contact fields were put into our contact editor, any of the FieldText components could be clicked and opened, and any of the RemoveButton components could be clicked and opened, all - at the same time. We would like this behavior to be some what modal - instead, encouraging the user to either accept or cancel the current - action before moving onto a new action. + at the same time. This leads to situations where the users actions + are ambiguous + + \image declarative-reuse-focus.png - In the tutorial we do this with a property of our top level component - to handle whether we are in this state or not. + To counteract this we will add a property of the root element to indicate + when an element has 'grabbed' mouse interaction, preventing other + clickable elements from reacting. \snippet declarative/tutorials/contacts/2_Reuse/4/Contact.qml grab property - And in the code where we want to check or avoid allowing mouse interaction. + The code that we want to disable then simply needs to check this property before + acting. \snippet declarative/tutorials/contacts/2_Reuse/4/RemoveButton.qml grab - Handling Key and Mouse focus in QML is quite likely to change before + \note Handling Key and Mouse focus in QML is quite likely to change before the Qt 4.6 release. */ @@ -618,13 +658,13 @@ Its important then to try and minimize the complexity of the delegate. This can be done by delaying the loading of the component. By using the qml property - of the Item component, we can delay building the Contact.qml item until the user + of the \l{qml-item}{Item} component, we can delay building the Contact.qml item until the user attempts to open the list. \snippet declarative/tutorials/contacts/3_Collections/3/ContactView.qml setting qml Each item has a qml property that represents the filename for the contents of - a special qmlItem child of the Item. By setting the qml property of the Details + a special qmlItem child of the \l{qml-item}{Item}. By setting the qml property of the Details component on clicking the mouse region, the more complex component isn't loaded until needed. The down side about this though is the properties of Contact cannot be set until the item is loaded. This requires using the Bind diff --git a/examples/declarative/tutorials/contacts/1_Drawing_and_Animation/4a/RemoveButton.qml b/examples/declarative/tutorials/contacts/1_Drawing_and_Animation/4a/RemoveButton.qml new file mode 100644 index 0000000..ce8459d --- /dev/null +++ b/examples/declarative/tutorials/contacts/1_Drawing_and_Animation/4a/RemoveButton.qml @@ -0,0 +1,117 @@ +Rect { + id: removeButton + width: 30 + height: 30 + color: "red" + radius: 5 +//! [script] + resources: [ + Script { + function toggle() { + if (removeButton.state == 'opened') { + removeButton.state = ''; + } else { + removeButton.state = 'opened'; + } + } + + } + ] +//! [script] +//! [mouse region] + Image { + id: trashIcon + width: 22 + height: 22 + anchors.right: parent.right + anchors.rightMargin: 4 + anchors.verticalCenter: parent.verticalCenter + source: "../../shared/pics/trash.png" + opacity: 1 + MouseRegion { + id: trashMouseRegion + anchors.fill: parent + } + Connection { + sender: trashMouseRegion + signal: clicked() + script: { + toggle() + } + } + } +//! [mouse region] + Image { + id: cancelIcon + width: 22 + height: 22 + anchors.right: parent.right + anchors.rightMargin: 4 + anchors.verticalCenter: parent.verticalCenter + source: "../../shared/pics/cancel.png" + opacity: 0 + MouseRegion { + anchors.fill: parent + onClicked: { toggle() } + } + } + Image { + id: confirmIcon + width: 22 + height: 22 + anchors.left: parent.left + anchors.leftMargin: 4 + anchors.verticalCenter: parent.verticalCenter + source: "../../shared/pics/ok.png" + opacity: 0 + MouseRegion { + anchors.fill: parent + onClicked: { toggle() } + } + } + Text { + id: text + anchors.verticalCenter: parent.verticalCenter + anchors.left: confirmIcon.right + anchors.leftMargin: 4 + anchors.right: cancelIcon.left + anchors.rightMargin: 4 + font.bold: true + color: "white" + hAlign: AlignHCenter + text: "Remove" + opacity: 0 + } +//! [states] + states: [ + State { + name: "opened" + SetProperty { + target: removeButton + property: "width" + value: 230 + } + SetProperty { + target: text + property: "opacity" + value: 1 + } + SetProperty { + target: confirmIcon + property: "opacity" + value: 1 + } + SetProperty { + target: cancelIcon + property: "opacity" + value: 1 + } + SetProperty { + target: trashIcon + property: "opacity" + value: 0 + } + } + ] +//! [states] +} diff --git a/examples/declarative/tutorials/contacts/2_Reuse/1b/BlueRect.qml b/examples/declarative/tutorials/contacts/2_Reuse/1b/BlueRect.qml new file mode 100644 index 0000000..92893f6 --- /dev/null +++ b/examples/declarative/tutorials/contacts/2_Reuse/1b/BlueRect.qml @@ -0,0 +1,33 @@ +//! [all] +Rect { + width: 100 + height: 100 + color: "blue" + resources: [ + Component { + id: redRectangle + Rect { + width: 30 + height: 30 + color: "red" + radius: 5 + } + } + ] + ComponentInstance { + component: redRectangle + anchors.right: parent.right + anchors.top: parent.top + } + ComponentInstance { + component: redRectangle + anchors.left: parent.left + anchors.top: parent.top + } + ComponentInstance { + component: redRectangle + anchors.left: parent.left + anchors.bottom: parent.bottom + } +} +//! [all] diff --git a/examples/declarative/tutorials/contacts/2_Reuse/1b/ContactField.qml b/examples/declarative/tutorials/contacts/2_Reuse/1b/ContactField.qml deleted file mode 100644 index 1366548..0000000 --- a/examples/declarative/tutorials/contacts/2_Reuse/1b/ContactField.qml +++ /dev/null @@ -1,29 +0,0 @@ -import "lib" -Item { - id: contactField - clip: true - width: 230 - height: 30 - RemoveButton { - id: removeButton - anchors.right: parent.right - anchors.top: parent.top - anchors.bottom: parent.bottom - } - Text { - id: fieldText - width: contactField.width-80 - anchors.right: removeButton.left - anchors.rightMargin: 10 - anchors.verticalCenter: parent.verticalCenter - font.bold: true - color: "black" - text: 123123 - } - Image { - source: "../../shared/pics/phone.png" - anchors.right: fieldText.left - anchors.rightMargin: 10 - anchors.verticalCenter: parent.verticalCenter - } -} diff --git a/examples/declarative/tutorials/contacts/2_Reuse/2/RemoveButton.qml b/examples/declarative/tutorials/contacts/2_Reuse/2/RemoveButton.qml index 45b1899..dc49d8e 100644 --- a/examples/declarative/tutorials/contacts/2_Reuse/2/RemoveButton.qml +++ b/examples/declarative/tutorials/contacts/2_Reuse/2/RemoveButton.qml @@ -62,10 +62,12 @@ Rect { anchors.verticalCenter: parent.verticalCenter source: "../../shared/pics/ok.png" opacity: 0 +//! [use signal] MouseRegion { anchors.fill: parent onClicked: { toggle(); removeButton.confirmed.emit() } } +//! [use signal] } Text { id: text @@ -83,11 +85,13 @@ Rect { states: [ State { name: "opened" +//! [use width] SetProperty { target: removeButton property: "width" value: removeButton.expandedWidth } +//! [use width] SetProperty { target: text property: "opacity" diff --git a/src/declarative/extra/qmlsqlconnection.cpp b/src/declarative/extra/qmlsqlconnection.cpp index a39aa6f..25ab033 100644 --- a/src/declarative/extra/qmlsqlconnection.cpp +++ b/src/declarative/extra/qmlsqlconnection.cpp @@ -79,13 +79,14 @@ public: Qml the query should connect using its name. \qml - <SqlConnection id="myConnection"> - <name>qmlConnection</name> - <driver>QSQLITE</driver> - <databaseName>"mydb.sqlite"</databaseName> - </SqlConnection> - <SqlQuery id="listmodel" connection="{myConnection}">SELECT * FROM mytable</SqlQuery> - <SqlQuery id="othermodel" connection="qmlConnection">SELECT * FROM myothertable</SqlQuery> + SqlConnection { + id: myConnection + name: "qmlConnection" + driver: "QSQLITE" + databaseName: "mydb.sqlite" + } + SqlQuery { id: listmodel; connection: myConnection; query: "SELECT * FROM mytable" } + SqlQuery { id: othermodel; connection: "qmlConnection"; query: "SELECT * FROM myothertable" } \endqml */ @@ -99,34 +100,34 @@ public: */ /*! - \qmlproperty QStringList SqlConnection::tables + \qmlproperty list<string> SqlConnection::tables Defines the set of tables that exist in the database for the connection. */ /*! - \qmlproperty QString SqlConnection::databaseName + \qmlproperty string SqlConnection::databaseName Defines the connection's database name. This is used when opening the connection to the database. */ /*! - \qmlproperty QString SqlConnection::driver + \qmlproperty string SqlConnection::driver Defines the driver type of the connection. This is used when opening the connection to the database. */ /*! - \qmlproperty QString SqlConnection::connectOptions + \qmlproperty string SqlConnection::connectOptions Defines the options used when connecting to the database. These are used when opening the connection to the database. */ /*! - \qmlproperty QString SqlConnection::hostName + \qmlproperty string SqlConnection::hostName Defines the connection's host name. This is used when opening the connection to the database. @@ -140,21 +141,21 @@ public: */ /*! - \qmlproperty QString SqlConnection::userName + \qmlproperty string SqlConnection::userName Defines the connection's user name. This is used when opening the connection to the database. */ /*! - \qmlproperty QString SqlConnection::password + \qmlproperty string SqlConnection::password Defines the connection's password. This is used when opening the connection to the database. */ /*! - \qmlproperty QString SqlConnection::lastError + \qmlproperty string SqlConnection::lastError Defines the last error, if one occurred, when working with the database. If the error occurred in conjunction with an SQL query the error will be diff --git a/src/declarative/extra/qmlsqlquery.cpp b/src/declarative/extra/qmlsqlquery.cpp index 70b3bdd..5bd1459 100644 --- a/src/declarative/extra/qmlsqlquery.cpp +++ b/src/declarative/extra/qmlsqlquery.cpp @@ -77,18 +77,19 @@ public: values will only apply when the SqlQuery exec() slot is called. \qml - <SqlQuery> - SELECT * FROM mytable WHERE name LIKE :value - <bindings> - <SqlBind name=":value" value="{searchText + '%'}"/> - </bindings> - </SqlQuery> - <SqlQuery> - SELECT * FROM mytable WHERE type = ? - <bindings> - <SqlBind value="simple"/> - </bindings> - <SqlQuery> + SqlQuery { + query: "SELECT * FROM mytable WHERE name LIKE :value" + bindings: SqlBind { + name: ":value" + value: searchText + '%' + } + } + SqlQuery { + query: "SELECT * FROM mytable WHERE type = ?" + bindings: SqlBind { + value: "simple" + } + } \endqml */ @@ -254,11 +255,12 @@ public: appropriate table column name for the result column. \qml - <SqlQuery connection="{qmlConnectionId}" query="DELETE FROM mytable"/> - <SqlQuery connection="connectionName"> - SELECT * FROM mytable - </SqlQuery> - <SqlQuery>SELECT id AS recordId, (firstName || ' ' || lastName) AS fullName FROM mytable</SqlQuery> + SqlQuery { connection: qmlConnectionId; query: "DELETE FROM mytable" } + SqlQuery { + connection: "connectionName" + query: "SELECT * FROM mytable" + } + SqlQuery { query: "SELECT id AS recordId, (firstName || ' ' || lastName) AS fullName FROM mytable" } \endqml */ diff --git a/src/declarative/fx/fx.pri b/src/declarative/fx/fx.pri index ef059c7..90820fa 100644 --- a/src/declarative/fx/fx.pri +++ b/src/declarative/fx/fx.pri @@ -17,8 +17,8 @@ HEADERS += \ fx/qfxgridview.h \ fx/qfxhighlightfilter.h \ fx/qfximage.h \ - fx/qfximageitem.h \ - fx/qfximageitem_p.h \ + fx/qfxpainteditem.h \ + fx/qfxpainteditem_p.h \ fx/qfximage_p.h \ fx/qfxitem.h \ fx/qfxitem_p.h \ @@ -28,8 +28,6 @@ HEADERS += \ fx/qfxlayouts_p.h \ fx/qfxmouseregion.h \ fx/qfxmouseregion_p.h \ - fx/qfxpainted.h \ - fx/qfxpainted_p.h \ fx/qfxparticles.h \ fx/qfxpath.h \ fx/qfxpath_p.h \ @@ -67,13 +65,12 @@ SOURCES += \ fx/qfxgridview.cpp \ fx/qfxhighlightfilter.cpp \ fx/qfximage.cpp \ - fx/qfximageitem.cpp \ + fx/qfxpainteditem.cpp \ fx/qfxitem.cpp \ fx/qfxkeyactions.cpp \ fx/qfxkeyproxy.cpp \ fx/qfxlayouts.cpp \ fx/qfxmouseregion.cpp \ - fx/qfxpainted.cpp \ fx/qfxparticles.cpp \ fx/qfxpath.cpp \ fx/qfxpathview.cpp \ diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index 838da30..106d551 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -135,7 +135,7 @@ QFxImage::~QFxImage() This property contains the image currently being displayed by this item, which may be an empty pixmap if nothing is currently displayed. If this - property is set, the src property will be unset. This property is intended + property is set, the source property will be unset. This property is intended to be used only in C++, not in QML. */ QPixmap QFxImage::pixmap() const @@ -790,7 +790,7 @@ QFxImage::Status QFxImage::status() const } /*! - \qmlproperty string Image::src + \qmlproperty string Image::source Image can handle any image format supported by Qt, loaded from any URL scheme supported by Qt. diff --git a/src/declarative/fx/qfxitem.cpp b/src/declarative/fx/qfxitem.cpp index ecc2d65..b737615 100644 --- a/src/declarative/fx/qfxitem.cpp +++ b/src/declarative/fx/qfxitem.cpp @@ -476,6 +476,10 @@ void QFxItem::setItemParent(QFxItem *parent) \property QFxItem::moveToParent Playing around with view2view transitions. */ + +/*! + \internal + */ void QFxItem::moveToParent(QFxItem *parent) { if (parent && itemParent()) { @@ -551,17 +555,18 @@ QFxItem *QFxItem::itemParent() const you, but it can come in handy in some cases. \qml - <Item> - <children> - <Text /> - <Rect /> - </children> - <resources> - <Component id="myComponent"> - <Text /> - </Component> - </resources> - </Item> + Item { + children: [ + Text {}, + Rect {} + ] + resources: [ + Component { + id: myComponent + Text {} + } + ] + } \endqml */ @@ -728,24 +733,24 @@ void QFxItemPrivate::children_clear() So you can write: \qml - <Item> - <Text /> - <Rect /> - <Script /> - </Item> + Item { + Text {} + Rect {} + Script {} + } \endqml instead of: \qml - <Item> - <children> - <Text /> - <Rect /> - </children> - <resources> - <Script/> - </resources> - </Item> + Item { + children: [ + Text {}, + Rect {} + ] + resources: [ + Script {} + ] + } \endqml data is a behind-the-scenes property: you should never need to explicitly @@ -792,6 +797,9 @@ QFxContents *QFxItem::contents() \property QFxItem::qmlItem */ +/*! \fn QFxItem *QFxItem::qmlItem() const + \internal + */ QFxItem *QFxItem::qmlItem() const { Q_D(const QFxItem); @@ -807,6 +815,13 @@ QFxItem *QFxItem::qmlItem() const dynamically set; otherwise an empty string is returned. */ +/*! \fn void QFxItem::qmlChanged() + This signal is emitted whenever the item's dynamic QML + string changes. + + \sa setQml() + */ + /*! \property QFxItem::qml This property holds the dynamic QML for the item. @@ -858,7 +873,14 @@ void QFxItem::setQml(const QString &qml) } } +/*! \fn void QFxItem::newChildCreated(const QString &url, QScriptValue v) + This signal is emitted with the \a url and the script value \a v, + when a new child is created. + */ +/*! + \internal + */ void QFxItem::qmlLoaded() { Q_D(QFxItem); @@ -916,7 +938,7 @@ void QFxItem::qmlLoaded() Defines the item's position and size relative to its parent. \qml - <Item x="100" y="100" width="100" height="100" /> + Item { x: 100; y: 100; width: 100; height: 100 } \endqml */ @@ -970,43 +992,72 @@ void QFxItem::qmlLoaded() \o \image declarative-item_stacking1.png \o Same \c z - later children above earlier children: \qml - <Item> - <Rect color="red" width="100" height="100" /> - <Rect color="blue" x="50" y="50" width="100" height="100" /> - </Item> + Item { + Rect { + color: "red" + width: 100; height: 100 + } + Rect { + color: "blue" + x: 50; y: 50; width: 100; height: 100 + } + } \endqml \row \o \image declarative-item_stacking2.png \o Higher \c z on top: \qml - <Item> - <Rect z="1" color="red" width="100" height="100" /> - <Rect color="blue" x="50" y="50" width="100" height="100" /> - </Item> + Item { + Rect { + z: 1 + color: "red" + width: 100; height: 100 + } + Rect { + color: "blue" + x: 50; y: 50; width: 100; height: 100 + } + } \endqml \row \o \image declarative-item_stacking3.png \o Same \c z - children above parents: \qml - <Item> - <Rect color="red" width="100" height="100"> - <Rect color="blue" x="50" y="50" width="100" height="100" /> - </Rect> - </Item> + Item { + Rect { + color: "red" + width: 100; height: 100 + Rect { + color: "blue" + x: 50; y: 50; width: 100; height: 100 + } + } + } \endqml \row \o \image declarative-item_stacking4.png \o Lower \c z below: \qml - <Item> - <Rect color="red" width="100" height="100"> - <Rect z="-1" color="blue" x="50" y="50" width="100" height="100" /> - </Rect> - </Item> + Item { + Rect { + color: "red" + width: 100; height: 100 + Rect { + z: -1 + color: "blue" + x: 50; y: 50; width: 100; height: 100 + } + } + } \endqml \endtable */ +/*! + This function is called to handle this item's changes in + geometry from \a oldGeometry to \a newGeometry. If the two + geometries are the same, it doesn't do anything. + */ void QFxItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) { @@ -1138,6 +1189,13 @@ void QFxItem::setFlipHorizontally(bool v) setFlip((QSimpleCanvasItem::Flip)(flip() & ~HorizontalFlip)); } +/*! \fn void QFxItem::keyPress(QFxKeyEvent *event) + This signal is emitted by keyPressEvent() for the \a event. + */ + +/*! \fn void QFxItem::keyRelease(QFxKeyEvent *event) + This signal is emitted by keyReleaseEvent() for the \a event. + */ /*! \reimp @@ -1179,8 +1237,8 @@ QRectF QFxItem::sceneBoundingRect() const refer to the item. For example: \qml - <Text id="myText" .../> - <Text text="{myText.text}"/> + Text { id: myText; ... } + Text { text: myText.text } \endqml The identifier is available throughout to the \l {components}{component} @@ -1195,8 +1253,8 @@ QRectF QFxItem::sceneBoundingRect() const refer to the item. For example: \qml - <Text id="myText" .../> - <Text text="{myText.text}"/> + Text { id: myText; ... } + Text { text: myText.text } \endqml The identifier is available throughout the \l {components}{component} @@ -1359,10 +1417,14 @@ QFxAnchorLine QFxItem::verticalCenter() const \o \image declarative-anchors_example.png \o Text anchored to Image, horizontally centered and vertically below, with a margin. \qml - <Image id="pic" .../> - <Text id="label" anchors.horizontalCenter="{pic.horizontalCenter}" - anchors.top="{pic.bottom}" - anchors.topMargin="5" .../> + Image { id: pic; ... } + Text { + id: label + anchors.horizontalCenter: pic.horizontalCenter + anchors.top: pic.bottom + anchors.topMargin: 5 + ... + } \endqml \row \o \image declarative-anchors_example2.png @@ -1371,9 +1433,13 @@ QFxAnchorLine QFxItem::verticalCenter() const property of both defaults to 0. \qml - <Image id="pic" .../> - <Text id="label" anchors.left="{pic.right}" - anchors.leftMargin="5" .../> + Image { id: pic; ... } + Text { + id: label + anchors.left: pic.right + anchors.leftMargin: 5 + ... + } \endqml \endtable @@ -1432,14 +1498,29 @@ void QFxItem::setBaselineOffset(int offset) \o \image declarative-rotation.png \o \qml - <Rect color="blue" width="100" height="100"> - <Rect color="green" width="25" height="25"/> - <Rect color="red" width="50" height="50" x="25" y="25" rotation="30"/> - </Rect> + Rect { + color: "blue" + width: 100; height: 100 + Rect { + color: "green" + width: 25; height: 25 + } + Rect { + color: "red" + x: 25; y: 25; width: 50; height: 50 + rotation: 30 + } + } \endqml \endtable */ +/*! \fn void QFxItem::rotationChanged() + This signal is emitted when the rotation property is changed. + + \sa setRotation() + */ + /*! \property QFxItem::rotation This property holds the rotation of the item in degrees. @@ -1495,10 +1576,19 @@ void QFxItem::setRotation(qreal rotation) \o \image declarative-scale.png \o \qml - <Rect color="blue" width="100" height="100"> - <Rect color="green" width="25" height="25"/> - <Rect color="red" width="50" height="50" x="25" y="25" scale="1.4"/> - </Rect> + Rect { + color: "blue" + width: 100; height: 100 + Rect { + color: "green" + width: 25; height: 25 + } + Rect { + color: "red" + x: 25; y: 25; width: 50; height: 50 + scale: 1.4 + } + } \endqml \endtable */ @@ -1546,21 +1636,32 @@ void QFxItem::setScale(qreal s) \o \image declarative-item_opacity1.png \o \qml - <Item> - <Rect color="red" width="100" height="100"> - <Rect color="blue" x="50" y="50" width="100" height="100" /> - </Rect> - </Item> + Item { + Rect { + color: "red" + width: 100; height: 100 + Rect { + color: "blue" + x: 50; y: 50; width: 100; height: 100 + } + } + } \endqml \row \o \image declarative-item_opacity2.png \o \qml - <Item> - <Rect opacity="0.5" color="red" width="100" height="100"> - <Rect color="blue" x="50" y="50" width="100" height="100" /> - </Rect> - </Item> + Item { + Rect { + opacity: 0.5 + color: "red" + width: 100; height: 100 + Rect { + color: "blue" + x: 50; y: 50; width: 100; height: 100 + } + } + } \endqml \endtable */ @@ -1592,12 +1693,20 @@ void QFxItem::setOpacity(qreal v) emit opacityChanged(); } +/*! + Returns a value indicating whether the mouse should + remain with this item. + */ bool QFxItem::keepMouseGrab() const { Q_D(const QFxItem); return d->_keepMouse; } +/*! + The flag indicating whether the mouse should remain + with this item is set to \a keep. + */ void QFxItem::setKeepMouseGrab(bool keep) { Q_D(QFxItem); @@ -1639,13 +1748,13 @@ QmlList<QObject *> *QFxItem::resources() This property holds a list of states defined by the item. \qml - <Item> - <states> - <State .../> - <State .../> - ... - </states> - </Item> + Item { + states: [ + State { ... }, + State { ... } + ... + ] + } \endqml \sa {states-transitions}{States and Transitions} @@ -1668,13 +1777,13 @@ QmlList<QmlState *>* QFxItem::states() This property holds a list of transitions defined by the item. \qml - <Item> - <transitions> - <Transition .../> - <Transition .../> - ... - </transitions> - </Item> + Item { + transitions: [ + Transition { ... }, + Transition { ... } + ... + ] + } \endqml \sa {states-transitions}{States and Transitions} @@ -1708,13 +1817,13 @@ QmlList<QmlTransition *>* QFxItem::transitions() that canvas (but the QML will still be considered valid). \qml - <Item> - <filter> - <Blur .../> - <Relection .../> - ... - </filter> - </Item> + Item { + filter: [ + Blur { ... }, + Relection { ... } + ... + ] + } \endqml */ @@ -1759,14 +1868,14 @@ QmlState *QFxItem::findState(const QString &name) const example: \qml - <Script> + Script { function toggle() { if (button.state == 'On') button.state = 'Off'; else button.state = 'On'; } - </Script> + } \endqml If the item is in its base state (i.e. no explicit state has been @@ -1785,14 +1894,14 @@ QmlState *QFxItem::findState(const QString &name) const example: \qml - <Script> + Script { function toggle() { if (button.state == 'On') button.state = 'Off'; else button.state = 'On'; } - </Script> + } \endqml If the item is in its base state (i.e. no explicit state has been diff --git a/src/declarative/fx/qfxpainted.cpp b/src/declarative/fx/qfxpainted.cpp deleted file mode 100644 index 68918c3..0000000 --- a/src/declarative/fx/qfxpainted.cpp +++ /dev/null @@ -1,194 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtDeclarative module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qfxpainted.h" -#include "qfxpainted_p.h" - - -QT_BEGIN_NAMESPACE -/*! - \internal - \class QFxPainted - \brief The QFxPainted class is an abstract base class for QFxView items that want cached painting. - - \ingroup group_coreitems - - This is a convenience class allowing easy use of cached painting within a custom item. - The contents of the item are cached behind the scenes. Any time you change the contents - you should call markDirty to make sure the cache is refreshed the next time painting occurs. - - \code - class GradientRect : public QFxPainted - { - Q_OBJECT - public: - GradientRect() : QFxPainted() - { - connect(this, SIGNAL(widthChanged()), this, SLOT(markDirty())); - connect(this, SIGNAL(heightChanged()), this, SLOT(markDirty())); - } - - void paint(QPainter *painter) - { - painter->fillRect(0, 0, width(), height(), QBrush(QLinearGradient(0,0,width(),height()))); - } - }; - \endcode - - \warning Dirty is only ever automatically set by QFxPainted at construction. Any other changes (including resizes) to the item need to be handled by the subclass (as in the example above). - \warning Frequent calls to markDirty will result in sub-optimal painting performance. -*/ - -/*! - Constructs a painted item with parent object \a parent. -*/ -QFxPainted::QFxPainted(QFxItem *parent) - : QFxItem(*(new QFxPaintedPrivate), parent) -{ - //### what options do we need to set? - setOptions(HasContents, true); -} - -/*! - Destroys the item. -*/ -QFxPainted::~QFxPainted() -{ -} - -/*! \internal -*/ -QFxPainted::QFxPainted(QFxPaintedPrivate &dd, QFxItem *parent) - : QFxItem(dd, parent) -{ - setOptions(HasContents, true); -} - -/*! - \fn QFxPainted::paint(QPainter *painter) - - Implement this method to paint the item using \a painter. - The painting will be cached and paint() will only be called again - if \l markDirty() has been called. - - \sa markDirty() -*/ - -/*! - The contents of the item are cached behind the scenes. Any time you change the contents - you should call markDirty to make sure the cache is refreshed the next time painting occurs. -*/ -void QFxPainted::markDirty() -{ - Q_D(QFxPainted); - if (d->dirty) - return; - d->dirty = true; - - // release cache memory (will be reallocated upon paintContents, if visible) -#if defined(QFX_RENDER_QPAINTER) - d->cachedImage = QImage(); -#elif defined(QFX_RENDER_OPENGL) - d->cachedTexture.clear(); -#endif - - update(); -} - -#if defined(QFX_RENDER_QPAINTER) -void QFxPainted::paintContents(QPainter &p) -{ - Q_D(QFxPainted); - if (d->dirty) { - d->cachedImage = QImage(width(), height(), QImage::Format_ARGB32_Premultiplied); - d->cachedImage.fill(0); - QPainter painter(&(d->cachedImage)); - paint(&painter); - d->dirty = false; - } - p.drawImage(0, 0, d->cachedImage); -} -#elif defined(QFX_RENDER_OPENGL2) -void QFxPainted::paintGLContents(GLPainter &painter) -{ - Q_D(QFxPainted); - if (d->dirty) { - QImage img = QImage(width(), height(), QImage::Format_ARGB32); - img.fill(0); - QPainter p(&(img)); - paint(&p); - d->cachedTexture.setImage(img); - d->dirty = false; - } - - //### mainly copied from QFxImage code - QGLShaderProgram *shader = painter.useTextureShader(); - - GLfloat vertices[8]; - GLfloat texVertices[8]; - GLTexture *tex = &d->cachedTexture; - - float widthV = d->cachedTexture.width(); - float heightV = d->cachedTexture.height(); - - vertices[0] = 0; vertices[1] = heightV; - vertices[2] = widthV; vertices[3] = heightV; - vertices[4] = 0; vertices[5] = 0; - vertices[6] = widthV; vertices[7] = 0; - - texVertices[0] = 0; texVertices[1] = 0; - texVertices[2] = 1; texVertices[3] = 0; - texVertices[4] = 0; texVertices[5] = 1; - texVertices[6] = 1; texVertices[7] = 1; - - shader->setAttributeArray(SingleTextureShader::Vertices, vertices, 2); - shader->setAttributeArray(SingleTextureShader::TextureCoords, texVertices, 2); - - glBindTexture(GL_TEXTURE_2D, tex->texture()); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - - shader->disableAttributeArray(SingleTextureShader::Vertices); - shader->disableAttributeArray(SingleTextureShader::TextureCoords); -} - -#endif - -QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxpainted.h b/src/declarative/fx/qfxpainted.h deleted file mode 100644 index 1f22414..0000000 --- a/src/declarative/fx/qfxpainted.h +++ /dev/null @@ -1,87 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtDeclarative module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QFXPAINTED_H -#define QFXPAINTED_H - -#include <qfxitem.h> - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) -/* -WARNING: INTENDED TO MERGE WITH QFxImageItem -*/ - -class QFxPaintedPrivate; -class Q_DECLARATIVE_EXPORT QFxPainted : public QFxItem -{ -Q_OBJECT -public: - QFxPainted(QFxItem *parent); - ~QFxPainted(); - - virtual void paint(QPainter *painter) = 0; - -#if defined(QFX_RENDER_QPAINTER) - void paintContents(QPainter &painter); -#elif defined(QFX_RENDER_OPENGL2) - void paintGLContents(GLPainter &); -#endif - -protected Q_SLOTS: - void markDirty(); - -protected: - QFxPainted(QFxPaintedPrivate &dd, QFxItem *parent); - -private: - Q_DISABLE_COPY(QFxPainted) - Q_DECLARE_PRIVATE(QFxPainted) -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QFXPAINTED_H diff --git a/src/declarative/fx/qfxpainted_p.h b/src/declarative/fx/qfxpainted_p.h deleted file mode 100644 index 68ac83e..0000000 --- a/src/declarative/fx/qfxpainted_p.h +++ /dev/null @@ -1,84 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtDeclarative module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 as published by the Free Software -** Foundation and appearing in the file LICENSE.LGPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU Lesser General Public License version 2.1 requirements -** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, Nokia gives you certain -** additional rights. These rights are described in the Nokia Qt LGPL -** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this -** package. -** -** GNU General Public License Usage -** Alternatively, this file may be used under the terms of the GNU -** General Public License version 3.0 as published by the Free Software -** Foundation and appearing in the file LICENSE.GPL included in the -** packaging of this file. Please review the following information to -** ensure the GNU General Public License version 3.0 requirements will be -** met: http://www.gnu.org/copyleft/gpl.html. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QFXPAINTED_P_H -#define QFXPAINTED_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qfxitem_p.h" -#if defined(QFX_RENDER_OPENGL) -#include "gltexture.h" -#endif - -QT_BEGIN_NAMESPACE - -class QFxPaintedPrivate : public QFxItemPrivate -{ - Q_DECLARE_PUBLIC(QFxPainted) - -public: - QFxPaintedPrivate() - : dirty(true) - { - } - - bool dirty; - -#if defined(QFX_RENDER_QPAINTER) - QSimpleCanvasConfig::Image cachedImage; -#elif defined(QFX_RENDER_OPENGL) - GLTexture cachedTexture; -#endif -}; - -QT_END_NAMESPACE - -#endif // QFXPAINTED_P_H diff --git a/src/declarative/fx/qfximageitem.cpp b/src/declarative/fx/qfxpainteditem.cpp index d751845..950b468 100644 --- a/src/declarative/fx/qfximageitem.cpp +++ b/src/declarative/fx/qfxpainteditem.cpp @@ -39,8 +39,8 @@ ** ****************************************************************************/ -#include "qfximageitem.h" -#include "qfximageitem_p.h" +#include "qfxpainteditem.h" +#include "qfxpainteditem_p.h" #include <QDebug> #include <QPen> @@ -57,30 +57,30 @@ QT_BEGIN_NAMESPACE /*! - \class QFxImageItem - \brief The QFxImageItem class is an abstract base class for QFxView items that want cached painting. + \class QFxPaintedItem + \brief The QFxPaintedItem class is an abstract base class for QFxView items that want cached painting. \ingroup group_coreitems - This is a convenience class allowing easy use of cached painting within a custom - item. The contents of the item are are cached behind the scenes. + This is a convenience class for implementing items that paint their contents + using a QPainter. The contents of the item are are cached behind the scenes. The dirtyCache() function should be called if the contents change to ensure the cache is refreshed the next time painting occurs. - To subclass QFxImageItem, you must reimplement drawContents() to draw + To subclass QFxPaintedItem, you must reimplement drawContents() to draw the contents of the item. */ /*! - \fn void QFxImageItem::drawContents(QPainter *painter, const QRect &rect) + \fn void QFxPaintedItem::drawContents(QPainter *painter, const QRect &rect) This function is called when the cache needs to be refreshed. When - sub-classing QFxImageItem this function should be implemented so as to + sub-classing QFxPaintedItem this function should be implemented so as to paint the contents of the item using the given \a painter for the area of the contents specified by \a rect. */ /*! - \property QFxImageItem::contentsSize + \property QFxPaintedItem::contentsSize \brief The size of the contents The contents size is the size of the item in regards to how it is painted @@ -89,7 +89,7 @@ QT_BEGIN_NAMESPACE */ /*! - \property QFxImageItem::smooth + \property QFxPaintedItem::smooth \brief Setting for whether smooth scaling is enabled. */ @@ -99,9 +99,9 @@ QT_BEGIN_NAMESPACE \sa clearCache() */ -void QFxImageItem::dirtyCache(const QRect& rect) +void QFxPaintedItem::dirtyCache(const QRect& rect) { - Q_D(QFxImageItem); + Q_D(QFxPaintedItem); for (int i=0; i < d->imagecache.count(); ) { if (d->imagecache[i]->area.intersects(rect)) { d->imagecache.removeAt(i); @@ -116,9 +116,9 @@ void QFxImageItem::dirtyCache(const QRect& rect) \sa dirtyCache() */ -void QFxImageItem::clearCache() +void QFxPaintedItem::clearCache() { - Q_D(QFxImageItem); + Q_D(QFxPaintedItem); qDeleteAll(d->imagecache); d->imagecache.clear(); } @@ -128,9 +128,9 @@ void QFxImageItem::clearCache() \sa setSmooth() */ -bool QFxImageItem::isSmooth() const +bool QFxPaintedItem::isSmooth() const { - Q_D(const QFxImageItem); + Q_D(const QFxPaintedItem); return d->smooth; } @@ -139,9 +139,9 @@ bool QFxImageItem::isSmooth() const \sa setContentsSize() */ -QSize QFxImageItem::contentsSize() const +QSize QFxPaintedItem::contentsSize() const { - Q_D(const QFxImageItem); + Q_D(const QFxPaintedItem); return d->contentsSize; } @@ -151,9 +151,9 @@ QSize QFxImageItem::contentsSize() const \sa isSmooth() */ -void QFxImageItem::setSmooth(bool smooth) +void QFxPaintedItem::setSmooth(bool smooth) { - Q_D(QFxImageItem); + Q_D(QFxPaintedItem); if (d->smooth == smooth) return; d->smooth = smooth; clearCache(); @@ -165,9 +165,9 @@ void QFxImageItem::setSmooth(bool smooth) \sa contentsSize() */ -void QFxImageItem::setContentsSize(const QSize &size) +void QFxPaintedItem::setContentsSize(const QSize &size) { - Q_D(QFxImageItem); + Q_D(QFxPaintedItem); if (d->contentsSize == size) return; d->contentsSize = size; clearCache(); @@ -175,20 +175,20 @@ void QFxImageItem::setContentsSize(const QSize &size) } /*! - Constructs a new QFxImageItem with the given \a parent. + Constructs a new QFxPaintedItem with the given \a parent. */ -QFxImageItem::QFxImageItem(QFxItem *parent) - : QFxItem(*(new QFxImageItemPrivate), parent) +QFxPaintedItem::QFxPaintedItem(QFxItem *parent) + : QFxItem(*(new QFxPaintedItemPrivate), parent) { init(); } /*! \internal - Constructs a new QFxImageItem with the given \a parent and + Constructs a new QFxPaintedItem with the given \a parent and initialized private data member \a dd. */ -QFxImageItem::QFxImageItem(QFxImageItemPrivate &dd, QFxItem *parent) +QFxPaintedItem::QFxPaintedItem(QFxPaintedItemPrivate &dd, QFxItem *parent) : QFxItem(dd, parent) { init(); @@ -197,14 +197,14 @@ QFxImageItem::QFxImageItem(QFxImageItemPrivate &dd, QFxItem *parent) /*! Destroys the image item. */ -QFxImageItem::~QFxImageItem() +QFxPaintedItem::~QFxPaintedItem() { } /*! \internal */ -void QFxImageItem::init() +void QFxPaintedItem::init() { connect(this,SIGNAL(widthChanged()),this,SLOT(clearCache())); connect(this,SIGNAL(heightChanged()),this,SLOT(clearCache())); @@ -215,17 +215,17 @@ void QFxImageItem::init() /*! \reimp */ -void QFxImageItem::paintContents(QPainter &p) +void QFxPaintedItem::paintContents(QPainter &p) #elif defined(QFX_RENDER_OPENGL) /*! \reimp */ -void QFxImageItem::paintGLContents(GLPainter &p) +void QFxPaintedItem::paintGLContents(GLPainter &p) #else #error "What render?" #endif { - Q_D(QFxImageItem); + Q_D(QFxPaintedItem); const QRect content(QPoint(0,0),d->contentsSize); if (content.width() <= 0 || content.height() <= 0) return; @@ -316,7 +316,7 @@ void QFxImageItem::paintGLContents(GLPainter &p) qp.translate(-r.x(),-r.y()); drawContents(&qp, r); } - QFxImageItemPrivate::ImageCacheItem *newitem = new QFxImageItemPrivate::ImageCacheItem; + QFxPaintedItemPrivate::ImageCacheItem *newitem = new QFxPaintedItemPrivate::ImageCacheItem; newitem->area = r; #if defined(QFX_RENDER_QPAINTER) newitem->image = QSimpleCanvasConfig::Image(QSimpleCanvasConfig::toImage(img)); diff --git a/src/declarative/fx/qfximageitem.h b/src/declarative/fx/qfxpainteditem.h index 9ffd44e..015a035 100644 --- a/src/declarative/fx/qfximageitem.h +++ b/src/declarative/fx/qfxpainteditem.h @@ -51,17 +51,14 @@ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Declarative) -/* -WARNING: SHORT TERM CLASS. INTENDED TO MERGE INTO QFxPainted -*/ -class QFxImageItemPrivate; -class Q_DECLARATIVE_EXPORT QFxImageItem : public QFxItem +class QFxPaintedItemPrivate; +class Q_DECLARATIVE_EXPORT QFxPaintedItem : public QFxItem { Q_OBJECT public: - QFxImageItem(QFxItem *parent=0); - ~QFxImageItem(); + QFxPaintedItem(QFxItem *parent=0); + ~QFxPaintedItem(); Q_PROPERTY(QSize contentsSize READ contentsSize WRITE setContentsSize); Q_PROPERTY(bool smooth READ isSmooth WRITE setSmooth); @@ -78,7 +75,7 @@ public: void setSmooth(bool); void setContentsSize(const QSize &); protected: - QFxImageItem(QFxImageItemPrivate &dd, QFxItem *parent); + QFxPaintedItem(QFxPaintedItemPrivate &dd, QFxItem *parent); virtual void drawContents(QPainter *p, const QRect &) = 0; @@ -88,10 +85,10 @@ protected Q_SLOTS: private: void init(); - Q_DISABLE_COPY(QFxImageItem) - Q_DECLARE_PRIVATE(QFxImageItem) + Q_DISABLE_COPY(QFxPaintedItem) + Q_DECLARE_PRIVATE(QFxPaintedItem) }; -QML_DECLARE_TYPE(QFxImageItem); +QML_DECLARE_TYPE(QFxPaintedItem); QT_END_NAMESPACE diff --git a/src/declarative/fx/qfximageitem_p.h b/src/declarative/fx/qfxpainteditem_p.h index 80450ec..b0432ac 100644 --- a/src/declarative/fx/qfximageitem_p.h +++ b/src/declarative/fx/qfxpainteditem_p.h @@ -62,12 +62,12 @@ QT_BEGIN_NAMESPACE -class QFxImageItemPrivate : public QFxItemPrivate +class QFxPaintedItemPrivate : public QFxItemPrivate { - Q_DECLARE_PUBLIC(QFxImageItem) + Q_DECLARE_PUBLIC(QFxPaintedItem) public: - QFxImageItemPrivate() + QFxPaintedItemPrivate() : max_imagecache_size(1000*1000), smooth(false) { } diff --git a/src/declarative/fx/qfxparticles.cpp b/src/declarative/fx/qfxparticles.cpp index 0ac537a..8535a73 100644 --- a/src/declarative/fx/qfxparticles.cpp +++ b/src/declarative/fx/qfxparticles.cpp @@ -113,8 +113,10 @@ QML_DEFINE_TYPE(QFxParticleMotion,ParticleMotion); \brief The QFxParticleMotion class is the base class for particle motion. This class causes the particles to remain static. +*/ - \sa QFxParticles +/*! + Constructs a QFxParticleMotion with parent object \a parent. */ QFxParticleMotion::QFxParticleMotion(QObject *parent) : QObject(parent) @@ -161,8 +163,6 @@ void QFxParticleMotion::destroy(QFxParticle &particle) \class QFxParticleMotionLinear \ingroup group_effects \brief The QFxParticleMotionLinear class moves the particles linearly. - - \sa QFxParticles */ QML_DEFINE_TYPE(QFxParticleMotionLinear,ParticleMotionLinear); @@ -185,8 +185,6 @@ void QFxParticleMotionLinear::advance(QFxParticle &p, int interval) \class QFxParticleMotionGravity \ingroup group_effects \brief The QFxParticleMotionGravity class moves the particles towards a point. - - \sa QFxParticles */ QML_DEFINE_TYPE(QFxParticleMotionGravity,ParticleMotionGravity); @@ -277,8 +275,6 @@ Rect { The particles will continue roughly in the original direction, however will randomly drift to each side. - - \sa QFxParticles */ /*! diff --git a/src/declarative/fx/qfxtextedit.cpp b/src/declarative/fx/qfxtextedit.cpp index 84e209b..a1b5484 100644 --- a/src/declarative/fx/qfxtextedit.cpp +++ b/src/declarative/fx/qfxtextedit.cpp @@ -103,7 +103,7 @@ TextEdit { Constructs a new QFxTextEdit. */ QFxTextEdit::QFxTextEdit(QFxItem *parent) -: QFxImageItem(*(new QFxTextEditPrivate), parent) +: QFxPaintedItem(*(new QFxTextEditPrivate), parent) { Q_D(QFxTextEdit); d->init(); @@ -113,7 +113,7 @@ QFxTextEdit::QFxTextEdit(QFxItem *parent) \internal */ QFxTextEdit::QFxTextEdit(QFxTextEditPrivate &dd, QFxItem *parent) - : QFxImageItem(dd, parent) + : QFxPaintedItem(dd, parent) { Q_D(QFxTextEdit); d->init(); @@ -383,7 +383,7 @@ void QFxTextEdit::geometryChanged(const QRectF &newGeometry, { if (newGeometry.width() != oldGeometry.width()) updateSize(); - QFxImageItem::geometryChanged(newGeometry, oldGeometry); + QFxPaintedItem::geometryChanged(newGeometry, oldGeometry); } /*! @@ -393,7 +393,7 @@ void QFxTextEdit::dump(int depth) { QByteArray ba(depth * 4, ' '); qWarning() << ba.constData() << propertyInfo(); - QFxImageItem::dump(depth); + QFxPaintedItem::dump(depth); } /*! @@ -412,7 +412,7 @@ QString QFxTextEdit::propertyInfo() const void QFxTextEdit::componentComplete() { Q_D(QFxTextEdit); - QFxImageItem::componentComplete(); + QFxPaintedItem::componentComplete(); if (d->dirty) { updateSize(); d->dirty = false; @@ -588,7 +588,7 @@ Handles the given focus \a event. void QFxTextEdit::focusInEvent(QFocusEvent *event) { Q_D(QFxTextEdit); - QFxImageItem::focusInEvent(event); + QFxPaintedItem::focusInEvent(event); d->control->processEvent(event, QPointF(0, 0)); } @@ -599,7 +599,7 @@ Handles the given focus \a event. void QFxTextEdit::focusOutEvent(QFocusEvent *event) { Q_D(QFxTextEdit); - QFxImageItem::focusOutEvent(event); + QFxPaintedItem::focusOutEvent(event); d->control->processEvent(event, QPointF(0, 0)); } @@ -638,7 +638,7 @@ void QFxTextEdit::mousePressEvent(QGraphicsSceneMouseEvent *event) event->setAccepted(me->isAccepted()); delete me; if (!event->isAccepted()) - QFxImageItem::mousePressEvent(event); + QFxPaintedItem::mousePressEvent(event); } /*! @@ -653,7 +653,7 @@ void QFxTextEdit::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) event->setAccepted(me->isAccepted()); delete me; if (!event->isAccepted()) - QFxImageItem::mousePressEvent(event); + QFxPaintedItem::mousePressEvent(event); } /*! @@ -668,7 +668,7 @@ void QFxTextEdit::mouseMoveEvent(QGraphicsSceneMouseEvent *event) event->setAccepted(me->isAccepted()); delete me; if (!event->isAccepted()) - QFxImageItem::mousePressEvent(event); + QFxPaintedItem::mousePressEvent(event); } /*! diff --git a/src/declarative/fx/qfxtextedit.h b/src/declarative/fx/qfxtextedit.h index be84a3c..b017635 100644 --- a/src/declarative/fx/qfxtextedit.h +++ b/src/declarative/fx/qfxtextedit.h @@ -43,7 +43,7 @@ #define QFXTEXTEDIT_H #include <qfxtext.h> -#include <qfximageitem.h> +#include <qfxpainteditem.h> #include <QtGui/qtextdocument.h> #include <QtGui/qtextoption.h> @@ -60,7 +60,7 @@ QT_MODULE(Declarative) WARNING: SHORT TERM CLASS. INTENDED TO MERGE INTO QFxTextItem */ class QFxTextEditPrivate; -class Q_DECLARATIVE_EXPORT QFxTextEdit : public QFxImageItem +class Q_DECLARATIVE_EXPORT QFxTextEdit : public QFxPaintedItem { Q_OBJECT Q_ENUMS(VAlignment) diff --git a/src/declarative/fx/qfxtextedit_p.h b/src/declarative/fx/qfxtextedit_p.h index aa07484..b583dbe 100644 --- a/src/declarative/fx/qfxtextedit_p.h +++ b/src/declarative/fx/qfxtextedit_p.h @@ -54,7 +54,7 @@ // #include "qfxitem.h" -#include "qfximageitem_p.h" +#include "qfxpainteditem_p.h" #include "qml.h" @@ -62,7 +62,7 @@ QT_BEGIN_NAMESPACE class QTextLayout; class QTextDocument; class QTextControl; -class QFxTextEditPrivate : public QFxImageItemPrivate +class QFxTextEditPrivate : public QFxPaintedItemPrivate { Q_DECLARE_PUBLIC(QFxTextEdit) diff --git a/src/declarative/fx/qfxwebview.cpp b/src/declarative/fx/qfxwebview.cpp index dac8ced..3f05846 100644 --- a/src/declarative/fx/qfxwebview.cpp +++ b/src/declarative/fx/qfxwebview.cpp @@ -68,7 +68,7 @@ #include "qfxwebview.h" #include <qsimplecanvasfilter.h> -#include <private/qfxitem_p.h> +#include <private/qfxpainteditem_p.h> QT_BEGIN_NAMESPACE QML_DEFINE_TYPE(QFxWebView,WebView); @@ -142,14 +142,14 @@ public: }; -class QFxWebViewPrivate : public QFxItemPrivate +class QFxWebViewPrivate : public QFxPaintedItemPrivate { Q_DECLARE_PUBLIC(QFxWebView) public: QFxWebViewPrivate() - : page(0), idealwidth(0), idealheight(0), interactive(true), lastPress(0), lastRelease(0), mouseX(0), mouseY(0), - smooth(true), max_imagecache_size(100000), progress(1.0), pending(PendingNone) + : QFxPaintedItemPrivate(), page(0), idealwidth(0), idealheight(0), interactive(true), lastPress(0), lastRelease(0), mouseX(0), mouseY(0), + max_imagecache_size(100000), progress(1.0), pending(PendingNone) { } @@ -189,7 +189,6 @@ public: bool interactive; QMouseEvent *lastPress, *lastRelease; int mouseX, mouseY; - bool smooth; int max_imagecache_size; qreal progress; QBasicTimer dcTimer; @@ -254,13 +253,13 @@ public: */ QFxWebView::QFxWebView(QFxItem *parent) - : QFxItem(*(new QFxWebViewPrivate), parent) + : QFxPaintedItem(*(new QFxWebViewPrivate), parent) { init(); } QFxWebView::QFxWebView(QFxWebViewPrivate &dd, QFxItem *parent) - : QFxItem(dd, parent) + : QFxPaintedItem(dd, parent) { init(); } @@ -284,7 +283,7 @@ void QFxWebView::init() void QFxWebView::componentComplete() { - QFxItem::componentComplete(); + QFxPaintedItem::componentComplete(); Q_D(QFxWebView); switch (d->pending) { case QFxWebViewPrivate::PendingUrl: @@ -460,28 +459,6 @@ void QFxWebView::setInteractive(bool i) emit interactiveChanged(); } -/*! - \qmlproperty bool WebView::smooth - This property holds hints as to whether the item should be drawn anti-aliased. -*/ -/*! - \property QFxWebView::smooth - \brief hints as to whether the item should be drawn anti-aliased. -*/ -bool QFxWebView::smooth() const -{ - Q_D(const QFxWebView); - return d->smooth; -} - -void QFxWebView::setSmooth(bool i) -{ - Q_D(QFxWebView); - if (d->smooth == i) return; - d->smooth = i; - update(); -} - void QFxWebView::updateCacheForVisibility() { Q_D(QFxWebView); @@ -514,13 +491,15 @@ void QFxWebView::geometryChanged(const QRectF &newGeometry, { if (newGeometry.size() != oldGeometry.size()) expandToWebPage(); - QFxItem::geometryChanged(newGeometry, oldGeometry); + QFxPaintedItem::geometryChanged(newGeometry, oldGeometry); } void QFxWebView::paintPage(const QRect& r) { Q_D(QFxWebView); - d->dirtyCache(r); + if (d->page->mainFrame()->contentsSize() != contentsSize()) + setContentsSize(d->page->mainFrame()->contentsSize()); + dirtyCache(r); update(); } @@ -575,96 +554,12 @@ void QFxWebView::dump(int depth) { QByteArray ba(depth * 4, ' '); qWarning() << ba.constData() << "url:" << url(); - QFxItem::dump(depth); + QFxPaintedItem::dump(depth); } -#if defined(QFX_RENDER_QPAINTER) -void QFxWebView::paintContents(QPainter &p) -#elif defined(QFX_RENDER_OPENGL) -void QFxWebView::paintGLContents(GLPainter &p) -#else -#error "What render?" -#endif +void QFxWebView::drawContents(QPainter *p, const QRect &r) { - Q_D(QFxWebView); - QWebFrame *frame = page()->mainFrame(); - const QRect content(QPoint(0,0),frame->contentsSize()); - - if (content.width() <= 0 || content.height() <= 0) - return; - -#if defined(QFX_RENDER_QPAINTER) - bool wasAA = p.testRenderHint(QPainter::Antialiasing); - bool wasSM = p.testRenderHint(QPainter::SmoothPixmapTransform); - p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->smooth); - QRectF clipf = p.clipRegion().boundingRect(); - const QRect clip = p.clipRegion().isEmpty() ? content : clipf.toRect(); -#elif defined(QFX_RENDER_OPENGL) - const QRectF clipf = p.sceneClipRect; - const QRect clip = mapFromScene(clipf).toRect(); -#endif - - QRegion topaint(clip); - topaint &= content; - QRegion uncached(content); - - int cachesize=0; - for (int i=0; i<d->imagecache.count(); ++i) { - QRect area = d->imagecache[i]->area; - if (topaint.contains(area)) { - p.drawImage(area, d->imagecache[i]->image); - topaint -= area; - d->imagecache[i]->age=0; - } else { - d->imagecache[i]->age++; - } - cachesize += area.width()*area.height(); - uncached -= area; - } - - if (!topaint.isEmpty()) { - // Find a sensible larger area, otherwise will paint lots of tiny images. - QRect biggerrect = topaint.boundingRect().adjusted(-64,-64,128,128); - cachesize += biggerrect.width() * biggerrect.height(); - while (d->imagecache.count() && cachesize > d->max_imagecache_size) { - int oldest=-1; - int age=-1; - for (int i=0; i<d->imagecache.count(); ++i) { - int a = d->imagecache[i]->age; - if (a > age) { - oldest = i; - age = a; - } - } - cachesize -= d->imagecache[oldest]->area.width()*d->imagecache[oldest]->area.height(); - uncached += d->imagecache[oldest]->area; - d->imagecache.removeAt(oldest); - } - const QRegion bigger = QRegion(biggerrect) & uncached; - const QVector<QRect> rects = bigger.rects(); - foreach (QRect r, rects) { - QImage img(r.size(),QImage::Format_ARGB32_Premultiplied); - img.fill(0); - { - QPainter qp(&img); - qp.translate(-r.x(),-r.y()); - frame->render(&qp,r); - } - QFxWebViewPrivate::ImageCacheItem *newitem = new QFxWebViewPrivate::ImageCacheItem; - newitem->area = r; -#if defined(QFX_RENDER_QPAINTER) - newitem->image = QSimpleCanvasConfig::Image(QSimpleCanvasConfig::toImage(img)); -#else - newitem->image.setImage(img); -#endif - d->imagecache.append(newitem); - p.drawImage(r, newitem->image); - } - } -#if defined(QFX_RENDER_QPAINTER) - p.setRenderHints(QPainter::Antialiasing, wasAA); - p.setRenderHints(QPainter::SmoothPixmapTransform, wasSM); -#endif + page()->mainFrame()->render(p,r); } QString QFxWebView::propertyInfo() const @@ -761,7 +656,7 @@ void QFxWebView::mousePressEvent(QGraphicsSceneMouseEvent *event) event->setAccepted(false); } if (!event->isAccepted()) - QFxItem::mousePressEvent(event); + QFxPaintedItem::mousePressEvent(event); } void QFxWebView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) @@ -775,7 +670,7 @@ void QFxWebView::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) event->setAccepted(false); } if (!event->isAccepted()) - QFxItem::mouseReleaseEvent(event); + QFxPaintedItem::mouseReleaseEvent(event); } void QFxWebView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) @@ -796,7 +691,7 @@ void QFxWebView::mouseMoveEvent(QGraphicsSceneMouseEvent *event) event->setAccepted(false); } if (!event->isAccepted()) - QFxItem::mouseMoveEvent(event); + QFxPaintedItem::mouseMoveEvent(event); } void QFxWebView::keyPressEvent(QKeyEvent* event) @@ -805,7 +700,7 @@ void QFxWebView::keyPressEvent(QKeyEvent* event) if (d->interactive) page()->event(event); if (!event->isAccepted()) - QFxItem::keyPressEvent(event); + QFxPaintedItem::keyPressEvent(event); } void QFxWebView::keyReleaseEvent(QKeyEvent* event) @@ -814,7 +709,7 @@ void QFxWebView::keyReleaseEvent(QKeyEvent* event) if (d->interactive) page()->event(event); if (!event->isAccepted()) - QFxItem::keyReleaseEvent(event); + QFxPaintedItem::keyReleaseEvent(event); } /*! diff --git a/src/declarative/fx/qfxwebview.h b/src/declarative/fx/qfxwebview.h index 6ba4601..afd5b0f 100644 --- a/src/declarative/fx/qfxwebview.h +++ b/src/declarative/fx/qfxwebview.h @@ -45,7 +45,7 @@ #include <QAction> #include <QUrl> #include <qfxglobal.h> -#include <qfxitem.h> +#include <qfxpainteditem.h> #include <QtNetwork/qnetworkaccessmanager.h> #include <QWebPage> @@ -74,7 +74,7 @@ private: }; -class Q_DECLARATIVE_EXPORT QFxWebView : public QFxItem +class Q_DECLARATIVE_EXPORT QFxWebView : public QFxPaintedItem { Q_OBJECT @@ -91,7 +91,6 @@ class Q_DECLARATIVE_EXPORT QFxWebView : public QFxItem Q_PROPERTY(int idealWidth READ idealWidth WRITE setIdealWidth NOTIFY idealWidthChanged) Q_PROPERTY(int idealHeight READ idealHeight WRITE setIdealHeight NOTIFY idealHeightChanged) Q_PROPERTY(QString url READ url WRITE setUrl NOTIFY urlChanged) - Q_PROPERTY(bool smooth READ smooth WRITE setSmooth) Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged) Q_PROPERTY(bool interactive READ interactive WRITE setInteractive NOTIFY interactiveChanged) @@ -128,9 +127,6 @@ public: int mouseX() const; int mouseY() const; - bool smooth() const; - void setSmooth(bool); - int idealWidth() const; void setIdealWidth(int); int idealHeight() const; @@ -146,11 +142,6 @@ public: virtual void dump(int depth); virtual QString propertyInfo() const; -#if defined(QFX_RENDER_QPAINTER) - void paintContents(QPainter &painter); -#elif defined(QFX_RENDER_OPENGL) - void paintGLContents(GLPainter &); -#endif QWebPage *page() const; void setPage(QWebPage *page); @@ -197,6 +188,9 @@ private Q_SLOTS: protected: QFxWebView(QFxWebViewPrivate &dd, QFxItem *parent); + + void drawContents(QPainter *, const QRect &); + void mousePressEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event); diff --git a/src/declarative/qml/parser/javascript.g b/src/declarative/qml/parser/javascript.g index 5482392..ec81a7a 100644 --- a/src/declarative/qml/parser/javascript.g +++ b/src/declarative/qml/parser/javascript.g @@ -2690,12 +2690,15 @@ PropertyNameAndValueListOpt: PropertyNameAndValueList ; tk.dval = yylval; tk.loc = yylloc; + yylloc = yyprevlloc; + yylloc.offset += yylloc.length; + yylloc.startColumn += yylloc.length; yylloc.length = 0; const QString msg = QString::fromUtf8("Missing `;'"); diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, - yyprevlloc.startLine, yyprevlloc.startColumn, msg)); + yylloc.startLine, yylloc.startColumn, msg)); first_token = &token_buffer[0]; last_token = &token_buffer[1]; diff --git a/src/declarative/qml/parser/javascriptparser.cpp b/src/declarative/qml/parser/javascriptparser.cpp index 185a824..897f0ce 100644 --- a/src/declarative/qml/parser/javascriptparser.cpp +++ b/src/declarative/qml/parser/javascriptparser.cpp @@ -1547,12 +1547,15 @@ case 312: { tk.dval = yylval; tk.loc = yylloc; + yylloc = yyprevlloc; + yylloc.offset += yylloc.length; + yylloc.startColumn += yylloc.length; yylloc.length = 0; const QString msg = QString::fromUtf8("Missing `;'"); diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, - yyprevlloc.startLine, yyprevlloc.startColumn, msg)); + yylloc.startLine, yylloc.startColumn, msg)); first_token = &token_buffer[0]; last_token = &token_buffer[1]; diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index b8f3921..d4003ab 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -545,7 +545,7 @@ bool QmlCompiler::compileObject(Object *obj, int ctxt) create.create.type = obj->type; output->bytecode << create; - COMPILE_CHECK(compileDynamicPropertiesAndSignals(obj)); + COMPILE_CHECK(compileDynamicMeta(obj)); if (obj->type != -1) { if (output->types.at(obj->type).component) { @@ -1212,10 +1212,12 @@ bool QmlCompiler::compilePropertyLiteralAssignment(QmlParser::Property *prop, return true; } -bool QmlCompiler::compileDynamicPropertiesAndSignals(QmlParser::Object *obj) +bool QmlCompiler::compileDynamicMeta(QmlParser::Object *obj) { // ### FIXME - Check that there is only one default property etc. - if (obj->dynamicProperties.isEmpty() && obj->dynamicSignals.isEmpty()) + if (obj->dynamicProperties.isEmpty() && + obj->dynamicSignals.isEmpty() && + obj->dynamicSlots.isEmpty()) return true; QMetaObjectBuilder builder; @@ -1263,6 +1265,14 @@ bool QmlCompiler::compileDynamicPropertiesAndSignals(QmlParser::Object *obj) builder.addSignal(s.name + "()"); } + int slotStart = obj->dynamicSlots.isEmpty()?-1:output->primitives.count(); + + for (int ii = 0; ii < obj->dynamicSlots.count(); ++ii) { + const Object::DynamicSlot &s = obj->dynamicSlots.at(ii); + builder.addSlot(s.name + "()"); + output->primitives << s.body; + } + if (obj->metatype) builder.setSuperClass(obj->metatype); @@ -1272,6 +1282,7 @@ bool QmlCompiler::compileDynamicPropertiesAndSignals(QmlParser::Object *obj) QmlInstruction store; store.type = QmlInstruction::StoreMetaObject; store.storeMeta.data = output->mos.count() - 1; + store.storeMeta.slotData = slotStart; store.line = obj->line; output->bytecode << store; diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h index 4acdcfa..e2b8388 100644 --- a/src/declarative/qml/qmlcompiler_p.h +++ b/src/declarative/qml/qmlcompiler_p.h @@ -163,7 +163,7 @@ private: QmlParser::Value *value, int ctxt); - bool compileDynamicPropertiesAndSignals(QmlParser::Object *obj); + bool compileDynamicMeta(QmlParser::Object *obj); void compileBinding(const QString &, QmlParser::Property *prop, int ctxt, const QMetaObject *, qint64); diff --git a/src/declarative/qml/qmlcomponent.cpp b/src/declarative/qml/qmlcomponent.cpp index b1beb9c..f0d23ee 100644 --- a/src/declarative/qml/qmlcomponent.cpp +++ b/src/declarative/qml/qmlcomponent.cpp @@ -173,6 +173,9 @@ QmlComponent::~QmlComponent() d->cc->release(); } +/*! + Returns the component's current \l{QmlComponent::Status} {status}. + */ QmlComponent::Status QmlComponent::status() const { Q_D(const QmlComponent); @@ -235,7 +238,8 @@ bool QmlComponent::isLoading() const */ /*! - Create a QmlComponent with no data. Set setData(). + Create a QmlComponent with no data and give it the specified + \a engine and \a parent. Set the data with setData(). */ QmlComponent::QmlComponent(QmlEngine *engine, QObject *parent) : QObject(*(new QmlComponentPrivate), parent) @@ -245,7 +249,10 @@ QmlComponent::QmlComponent(QmlEngine *engine, QObject *parent) } /*! - Create a QmlComponent from the given \a url. + Create a QmlComponent from the given \a url and give it the + specified \a parent and \a engine. + + \sa loadUrl() */ QmlComponent::QmlComponent(QmlEngine *engine, const QUrl &url, QObject *parent) : QObject(*(new QmlComponentPrivate), parent) @@ -256,9 +263,12 @@ QmlComponent::QmlComponent(QmlEngine *engine, const QUrl &url, QObject *parent) } /*! - Create a QmlComponent from the given XML \a data. If provided, \a filename - is used to set the component name, and to provide a base path for items - resolved by this component. + Create a QmlComponent from the given QML \a data and give it the + specified \a parent. If \a url is provided, it is used to set + the component name, and to provide a base path for items resolved + by this component. + + \sa setData() */ QmlComponent::QmlComponent(QmlEngine *engine, const QByteArray &data, const QUrl &url, QObject *parent) : QObject(*(new QmlComponentPrivate), parent) @@ -283,9 +293,9 @@ QmlComponent::QmlComponent(QmlEngine *engine, QmlCompiledComponent *cc, int star } /*! - Sets the QmlComponent to use the given XML \a data. If provided, - \a filename is used to set the component name, and to provide a base path - for items resolved by this component. + Sets the QmlComponent to use the given QML \a data. If \a url + is provided, it is used to set the component name and to provide + a base path for items resolved by this component. */ void QmlComponent::setData(const QByteArray &data, const QUrl &url) { @@ -451,8 +461,7 @@ QObject *QmlComponent::beginCreate(QmlContext *context) QmlContext *ctxt = new QmlContext(context, 0); - static_cast<QmlContextPrivate*>(ctxt->d_ptr)->component = d->cc; - static_cast<QmlContextPrivate*>(ctxt->d_ptr)->component->addref(); + static_cast<QmlContextPrivate*>(ctxt->d_ptr)->url = d->cc->url; ctxt->activate(); QmlVME vme; diff --git a/src/declarative/qml/qmlcontext.cpp b/src/declarative/qml/qmlcontext.cpp index 30857ad..68453c3 100644 --- a/src/declarative/qml/qmlcontext.cpp +++ b/src/declarative/qml/qmlcontext.cpp @@ -42,7 +42,6 @@ #include <qmlcontext.h> #include <private/qmlcontext_p.h> #include <private/qmlengine_p.h> -#include <private/qmlcompiledcomponent_p.h> #include <qmlengine.h> #include <qscriptengine.h> @@ -54,7 +53,7 @@ QT_BEGIN_NAMESPACE QmlContextPrivate::QmlContextPrivate() - : parent(0), engine(0), highPriorityCount(0), component(0) + : parent(0), engine(0), highPriorityCount(0) { } @@ -232,8 +231,6 @@ QmlContext::QmlContext(QmlContext *parentContext, QObject *parent) */ QmlContext::~QmlContext() { - Q_D(QmlContext); - if (d->component) d->component->release(); } @@ -344,7 +341,7 @@ QmlContext *QmlContext::activeContext() simply returned. If there is no containing component, an empty URL is returned. - \sa QmlEngine::componentUrl() + \sa QmlEngine::componentUrl(), setBaseUrl() */ QUrl QmlContext::resolvedUrl(const QUrl &src) { @@ -352,14 +349,14 @@ QUrl QmlContext::resolvedUrl(const QUrl &src) if (src.isRelative()) { if (ctxt) { while(ctxt) { - if (ctxt->d_func()->component) + if(ctxt->d_func()->url.isValid()) break; else ctxt = ctxt->parentContext(); } if (ctxt) - return ctxt->d_func()->component->url.resolved(src); + return ctxt->d_func()->url.resolved(src); } return QUrl(); } else { @@ -373,7 +370,7 @@ QUrl QmlContext::resolvedUrl(const QUrl &src) \l {QmlEngine::nameSpacePaths()} {namespace paths} of the context's engine, returning the resolved URL. - \sa QmlEngine::componentUrl() + \sa QmlEngine::componentUrl(), setBaseUrl() */ QUrl QmlContext::resolvedUri(const QUrl &src) { @@ -381,14 +378,14 @@ QUrl QmlContext::resolvedUri(const QUrl &src) if (src.isRelative()) { if (ctxt) { while(ctxt) { - if (ctxt->d_func()->component) + if (ctxt->d_func()->url.isValid()) break; else ctxt = ctxt->parentContext(); } if (ctxt) - return ctxt->d_func()->engine->componentUrl(src, ctxt->d_func()->component->url); + return ctxt->d_func()->engine->componentUrl(src, ctxt->d_func()->url); } return QUrl(); } else { @@ -396,6 +393,20 @@ QUrl QmlContext::resolvedUri(const QUrl &src) } } +/*! + Explicitly sets the url both resolveUri() and resolveUrl() will + use for relative references to \a baseUrl. + + Calling this function will override the url of the containing + component used by default. + + \sa resolvedUrl(), resolvedUri() +*/ +void QmlContext::setBaseUrl(const QUrl &baseUrl) +{ + d_func()->url = baseUrl; +} + void QmlContext::objectDestroyed(QObject *object) { Q_D(QmlContext); diff --git a/src/declarative/qml/qmlcontext.h b/src/declarative/qml/qmlcontext.h index 9e3b6d8..39d565a 100644 --- a/src/declarative/qml/qmlcontext.h +++ b/src/declarative/qml/qmlcontext.h @@ -80,6 +80,8 @@ public: QUrl resolvedUri(const QUrl &); QUrl resolvedUrl(const QUrl &); + void setBaseUrl(const QUrl &); + private Q_SLOTS: void objectDestroyed(QObject *); diff --git a/src/declarative/qml/qmlcontext_p.h b/src/declarative/qml/qmlcontext_p.h index 3772885..40848fb 100644 --- a/src/declarative/qml/qmlcontext_p.h +++ b/src/declarative/qml/qmlcontext_p.h @@ -69,7 +69,8 @@ public: QScriptValueList scopeChain; - QmlCompiledComponent *component; + QUrl url; + void init(); void dump(); diff --git a/src/declarative/qml/qmlcustomparser.cpp b/src/declarative/qml/qmlcustomparser.cpp index 544c469..06035b0 100644 --- a/src/declarative/qml/qmlcustomparser.cpp +++ b/src/declarative/qml/qmlcustomparser.cpp @@ -52,11 +52,11 @@ using namespace QmlParser; \brief The QmlCustomParser class allows you to add new arbitrary types to QML. \internal - By subclassing QmlCustomParser, you can add an XML parser for building a - particular type. + By subclassing QmlCustomParser, you can add an XML parser for + building a particular type. - The subclass must implement compile() and create(), and define itself in - the meta type system with one of the macros: + The subclass must implement compile() and create(), and define + itself in the meta type system with one of the macros: \code QML_DEFINE_CUSTOM_PARSER(Name, parserClass) @@ -67,33 +67,39 @@ using namespace QmlParser; \endcode */ -/*! +/* \fn QByteArray QmlCustomParser::compile(QXmlStreamReader& reader, bool *ok) - Upon entry to this function, \a reader is positioned on a QXmlStreamReader::StartElement - with the name specified when the class was defined with the QML_DEFINE_CUSTOM_PARSER macro. + Upon entry to this function, \a reader is positioned on a + QXmlStreamReader::StartElement with the name specified when the + class was defined with the QML_DEFINE_CUSTOM_PARSER macro. - The custom parser must consume tokens from \a reader until the EndElement matching the - initial start element is reached, or until error. + The custom parser must consume tokens from \a reader until the + EndElement matching the initial start element is reached, or until + error. On return, \c *ok indicates success. - The returned QByteArray contains data meaningful only to the custom parser; the - type engine will pass this same data to create() when making an instance of the data. + The returned QByteArray contains data meaningful only to the + custom parser; the type engine will pass this same data to + create() when making an instance of the data. - The QByteArray may be cached between executions of the system, so it must contain - correctly-serialized data (not, for example, pointers to stack objects). + The QByteArray may be cached between executions of the system, so + it must contain correctly-serialized data (not, for example, + pointers to stack objects). */ -/*! +/* \fn QVariant QmlCustomParser::create(const QByteArray &data) - This function returns a QVariant containing the value represented by \a data, which - is a block of data previously returned by a call to compile(). + This function returns a QVariant containing the value represented + by \a data, which is a block of data previously returned by a call + to compile(). - If the compile is for a type, the variant should be a pointer to the - correctly-named QObject subclass (i.e. the one defined by QML_DEFINE_TYPE for - the same-named type as this custom parser is defined for). + If the compile is for a type, the variant should be a pointer to + the correctly-named QObject subclass (i.e. the one defined by + QML_DEFINE_TYPE for the same-named type as this custom parser is + defined for). */ QmlCustomParserNode diff --git a/src/declarative/qml/qmldom.h b/src/declarative/qml/qmldom.h index 74ed27c..daca888 100644 --- a/src/declarative/qml/qmldom.h +++ b/src/declarative/qml/qmldom.h @@ -73,7 +73,6 @@ public: int version() const; QList<QmlError> errors() const; - QString loadError() const; bool load(QmlEngine *, const QByteArray &); QByteArray save() const; diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index 30848c1..bcea325 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -373,7 +373,7 @@ bool QmlEnginePrivate::loadCache(QmlBasicScriptNodeCache &cache, const QString & \code QmlEngine engine; - QmlComponent component("<Text text=\"Hello world!\"/>"); + QmlComponent component("Text { text: \"Hello world!\" }"); QFxItem *item = qobject_cast<QFxItem *>(component.create(&engine)); //add item to view, etc @@ -408,6 +408,9 @@ QmlEngine::~QmlEngine() { } +/*! + Clears the engine's internal component cache. + */ void QmlEngine::clearComponentCache() { Q_D(QmlEngine); @@ -582,8 +585,8 @@ void QmlEngine::setNetworkAccessManager(QNetworkAccessManager *network) } /*! - Returns the common QNetworkAccessManager used by all QML elements instantiated by - this engine. + Returns the common QNetworkAccessManager used by all QML elements + instantiated by this engine. The default implements no caching, cookiejar, etc., just a default QNetworkAccessManager. @@ -596,6 +599,9 @@ QNetworkAccessManager *QmlEngine::networkAccessManager() const return d->networkAccessManager; } +/*! + Returns the QmlContext for the \a object. + */ QmlContext *QmlEngine::contextForObject(const QObject *object) { QObjectPrivate *priv = QObjectPrivate::get(const_cast<QObject *>(object)); @@ -606,6 +612,11 @@ QmlContext *QmlEngine::contextForObject(const QObject *object) return data?data->context:0; } +/*! + Sets the QmlContext for the \a object to \a context. + If the \a object already has a context, a warning is + output, but the context is not changed. + */ void QmlEngine::setContextForObject(QObject *object, QmlContext *context) { QObjectPrivate *priv = QObjectPrivate::get(object); diff --git a/src/declarative/qml/qmlinstruction.cpp b/src/declarative/qml/qmlinstruction.cpp index 52677c2..0617913 100644 --- a/src/declarative/qml/qmlinstruction.cpp +++ b/src/declarative/qml/qmlinstruction.cpp @@ -68,7 +68,7 @@ void QmlCompiledComponent::dump(QmlInstruction *instr, int idx) qWarning() << idx << "\t" << line << "\t" << "CREATE_COMPONENT\t" << instr->createComponent.count; break; case QmlInstruction::StoreMetaObject: - qWarning() << idx << "\t" << line << "\t" << "STORE_META\t\t" << instr->storeMeta.data; + qWarning() << idx << "\t" << line << "\t" << "STORE_META\t\t" << instr->storeMeta.data << "\t" << instr->storeMeta.slotData; break; case QmlInstruction::StoreReal: qWarning() << idx << "\t" << line << "\t" << "STORE_REAL\t\t" << instr->storeReal.propertyIndex << "\t" << instr->storeReal.value; diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index 462f9e4..01bdfdd 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -177,6 +177,7 @@ public: } create; struct { int data; + int slotData; } storeMeta; struct { int value; diff --git a/src/declarative/qml/qmlmetaproperty.cpp b/src/declarative/qml/qmlmetaproperty.cpp index 1a511eb..14a45dc 100644 --- a/src/declarative/qml/qmlmetaproperty.cpp +++ b/src/declarative/qml/qmlmetaproperty.cpp @@ -261,6 +261,33 @@ QmlMetaProperty::QmlMetaProperty(const QmlMetaProperty &other) } /*! + \enum QmlMetaProperty::PropertyCategory + + This enum specifies a category of QML property. + + \value Unknown + \value InvalidProperty + \value Bindable + \value List + \value QmlList + \value Object + \value Normal + */ + +/*! + \enum QmlMetaProperty::Type + + This enum specifies a type of QML property. + + \value Invalid + \value Property + \value SignalProperty + \value Signal + \value Default + \value Attached +*/ + +/*! Returns the property category. */ QmlMetaProperty::PropertyCategory QmlMetaProperty::propertyCategory() const @@ -472,13 +499,17 @@ QStringList QmlMetaProperty::properties(QObject *obj) } /*! - Return the name of this property. + Return the name of this QML property. */ QString QmlMetaProperty::name() const { return d->name; } +/*! + Returns the \l{QMetaProperty} {Qt property} associated with + this QML property. + */ const QMetaProperty &QmlMetaProperty::property() const { return d->prop; @@ -1037,9 +1068,10 @@ quint32 QmlMetaProperty::save() const } /*! - Restore a QmlMetaProperty from a previously saved id. \a obj must be the - same object as used in the previous call to QmlMetaProperty::save(). Only - the bottom 24-bits are used, the high bits can be set to any value. + Restore a QmlMetaProperty from a previously saved \a id. + \a obj must be the same object as used in the previous call + to QmlMetaProperty::save(). Only the bottom 24-bits are + used, the high bits can be set to any value. */ void QmlMetaProperty::restore(quint32 id, QObject *obj) { diff --git a/src/declarative/qml/qmlparser.cpp b/src/declarative/qml/qmlparser.cpp index d862315..a943c4d 100644 --- a/src/declarative/qml/qmlparser.cpp +++ b/src/declarative/qml/qmlparser.cpp @@ -123,6 +123,15 @@ QmlParser::Object::DynamicSignal::DynamicSignal(const DynamicSignal &o) { } +QmlParser::Object::DynamicSlot::DynamicSlot() +{ +} + +QmlParser::Object::DynamicSlot::DynamicSlot(const DynamicSlot &o) +: name(o.name), body(o.body) +{ +} + QmlParser::Property::Property() : type(0), index(-1), value(0), isDefault(true), line(-1), column(-1) { diff --git a/src/declarative/qml/qmlparser_p.h b/src/declarative/qml/qmlparser_p.h index aeacee8..676e25e 100644 --- a/src/declarative/qml/qmlparser_p.h +++ b/src/declarative/qml/qmlparser_p.h @@ -123,11 +123,20 @@ namespace QmlParser QByteArray name; }; + struct DynamicSlot { + DynamicSlot(); + DynamicSlot(const DynamicSlot &); - // The list of dynamic properties described in the "properties" property + QByteArray name; + QString body; + }; + + // The list of dynamic properties QList<DynamicProperty> dynamicProperties; - // The list of dynamic signals described in the "signals" property + // The list of dynamic signals QList<DynamicSignal> dynamicSignals; + // The list of dynamic slots + QList<DynamicSlot> dynamicSlots; }; class Value : public QmlRefCount diff --git a/src/declarative/qml/qmlparserstatus.cpp b/src/declarative/qml/qmlparserstatus.cpp index 1f49553..71b7adf 100644 --- a/src/declarative/qml/qmlparserstatus.cpp +++ b/src/declarative/qml/qmlparserstatus.cpp @@ -49,6 +49,13 @@ QT_BEGIN_NAMESPACE */ /*! + Destroys the parser status instance. +*/ +QmlParserStatus::~QmlParserStatus() +{ +} + +/*! Invoked after class creation, but before any properties have been set. */ void QmlParserStatus::classBegin() diff --git a/src/declarative/qml/qmlparserstatus.h b/src/declarative/qml/qmlparserstatus.h index 1ec50ba..bb3691c 100644 --- a/src/declarative/qml/qmlparserstatus.h +++ b/src/declarative/qml/qmlparserstatus.h @@ -53,7 +53,7 @@ QT_MODULE(Declarative) class Q_DECLARATIVE_EXPORT QmlParserStatus { public: - virtual ~QmlParserStatus() {} + virtual ~QmlParserStatus(); virtual void classBegin(); virtual void classComplete(); diff --git a/src/declarative/qml/qmlpropertyvaluesource.cpp b/src/declarative/qml/qmlpropertyvaluesource.cpp index 78b0495..4770929 100644 --- a/src/declarative/qml/qmlpropertyvaluesource.cpp +++ b/src/declarative/qml/qmlpropertyvaluesource.cpp @@ -50,20 +50,26 @@ QT_BEGIN_NAMESPACE */ QML_DEFINE_NOCREATE_TYPE(QmlPropertyValueSource); +/*! + Constructs a QmlPropertyValueSource with parent \a parent. +*/ QmlPropertyValueSource::QmlPropertyValueSource(QObject *parent) : QObject(parent) { } +/*! + \internal + */ QmlPropertyValueSource::QmlPropertyValueSource(QObjectPrivate &dd, QObject *parent) : QObject(dd, parent) { } /*! - Set the target \a property for the value source. This method will be called - by the QML engine when assigning a value source. + Set the target \a property for the value source. This method will + be called by the QML engine when assigning a value source. The default implementation does nothing. */ diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index 81315c3..22ff4a5 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -521,31 +521,54 @@ bool ProcessAST::visit(AST::UiArrayBinding *node) bool ProcessAST::visit(AST::UiSourceElement *node) { QmlParser::Object *obj = currentObject(); - if (! (obj && obj->typeName == "Script")) { - QmlError error; - error.setDescription("JavaScript declaration outside Script element"); - error.setLine(node->firstSourceLocation().startLine); - error.setColumn(node->firstSourceLocation().startColumn); - _parser->_errors << error; - return false; - } - QString source; + bool isScript = (obj && obj->typeName == "Script"); - int line = 0; - if (AST::FunctionDeclaration *funDecl = AST::cast<AST::FunctionDeclaration *>(node->sourceElement)) { - line = funDecl->functionToken.startLine; - source = asString(funDecl); - } else if (AST::VariableStatement *varStmt = AST::cast<AST::VariableStatement *>(node->sourceElement)) { - // ignore variable declarations - line = varStmt->declarationKindToken.startLine; - } + if (!isScript) { - Value *value = new Value; - value->primitive = source; - value->line = line; + if (AST::FunctionDeclaration *funDecl = AST::cast<AST::FunctionDeclaration *>(node->sourceElement)) { + + if(funDecl->formals) { + QmlError error; + error.setDescription("Slot declarations must be parameterless"); + error.setLine(funDecl->lparenToken.startLine); + error.setColumn(funDecl->lparenToken.startColumn); + _parser->_errors << error; + return false; + } + + QString body = textAt(funDecl->lbraceToken, funDecl->rbraceToken); + Object::DynamicSlot slot; + slot.name = funDecl->name->asString().toUtf8(); + slot.body = body; + obj->dynamicSlots << slot; + } else { + QmlError error; + error.setDescription("JavaScript declaration outside Script element"); + error.setLine(node->firstSourceLocation().startLine); + error.setColumn(node->firstSourceLocation().startColumn); + _parser->_errors << error; + } + return false; - obj->getDefaultProperty()->addValue(value); + } else { + QString source; + + int line = 0; + if (AST::FunctionDeclaration *funDecl = AST::cast<AST::FunctionDeclaration *>(node->sourceElement)) { + line = funDecl->functionToken.startLine; + source = asString(funDecl); + } else if (AST::VariableStatement *varStmt = AST::cast<AST::VariableStatement *>(node->sourceElement)) { + // ignore variable declarations + line = varStmt->declarationKindToken.startLine; + } + + Value *value = new Value; + value->primitive = source; + value->line = line; + + obj->getDefaultProperty()->addValue(value); + } return false; } diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index ad3d1d5..ee7a881 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -320,7 +320,7 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in QFxCompilerTimer<QFxCompiler::InstrStoreMetaObject> cc; #endif QObject *target = stack.top(); - new QmlVMEMetaObject(target, mos.at(instr.storeMeta.data), comp); + new QmlVMEMetaObject(target, mos.at(instr.storeMeta.data), &comp->primitives, instr.storeMeta.slotData, comp); } break; diff --git a/src/declarative/qml/qmlvmemetaobject.cpp b/src/declarative/qml/qmlvmemetaobject.cpp index f7d2635..58708cf 100644 --- a/src/declarative/qml/qmlvmemetaobject.cpp +++ b/src/declarative/qml/qmlvmemetaobject.cpp @@ -44,13 +44,18 @@ #include <private/qmlrefcount_p.h> #include <QColor> #include <QDate> +#include <QtCore/qlist.h> +#include <QtCore/qdebug.h> +#include <qmlexpression.h> QT_BEGIN_NAMESPACE QmlVMEMetaObject::QmlVMEMetaObject(QObject *obj, - const QMetaObject *other, - QmlRefCount *rc) -: object(obj), ref(rc) + const QMetaObject *other, + QList<QString> *strData, + int slotData, + QmlRefCount *rc) +: object(obj), ref(rc), slotData(strData), slotDataIdx(slotData) { if (ref) ref->addref(); @@ -64,6 +69,7 @@ QmlVMEMetaObject::QmlVMEMetaObject(QObject *obj, data = new QVariant[propertyCount() - baseProp]; vTypes.resize(propertyCount() - baseProp); + // ### Optimize for (int ii = baseProp; ii < propertyCount(); ++ii) { QMetaProperty prop = property(ii); if ((int)prop.type() != -1) { @@ -72,6 +78,23 @@ QmlVMEMetaObject::QmlVMEMetaObject(QObject *obj, vTypes.setBit(ii - baseProp, true); } } + + baseSlot = -1; + slotCount = 0; + for (int ii = baseSig; ii < methodCount(); ++ii) { + QMetaMethod m = method(ii); + if (m.methodType() == QMetaMethod::Slot) { + if (baseSlot == -1) + baseSlot = ii; + } else { + if (baseSlot != -1) { + slotCount = ii - baseSlot; + break; + } + } + } + if(baseSlot != -1 && !slotCount) + slotCount = methodCount() - baseSlot; } QmlVMEMetaObject::~QmlVMEMetaObject() @@ -83,58 +106,69 @@ QmlVMEMetaObject::~QmlVMEMetaObject() int QmlVMEMetaObject::metaCall(QMetaObject::Call c, int id, void **a) { - if (id >= baseProp) { - int propId = id - baseProp; - bool needActivate = false; + if(c == QMetaObject::ReadProperty || c == QMetaObject::WriteProperty) { + if (id >= baseProp) { + int propId = id - baseProp; + bool needActivate = false; - if (vTypes.testBit(propId)) { - if (c == QMetaObject::ReadProperty) { - *reinterpret_cast<QVariant *>(a[0]) = data[propId]; - } else if (c == QMetaObject::WriteProperty) { - needActivate = - (data[propId] != *reinterpret_cast<QVariant *>(a[0])); - data[propId] = *reinterpret_cast<QVariant *>(a[0]); - } - } else { - if (c == QMetaObject::ReadProperty) { - switch(data[propId].type()) { - case QVariant::Int: - *reinterpret_cast<int *>(a[0]) = data[propId].toInt(); - break; - case QVariant::Bool: - *reinterpret_cast<bool *>(a[0]) = data[propId].toBool(); - break; - case QVariant::Double: - *reinterpret_cast<double *>(a[0]) = data[propId].toDouble(); - break; - case QVariant::String: - *reinterpret_cast<QString *>(a[0]) = data[propId].toString(); - break; - case QVariant::Color: - *reinterpret_cast<QColor *>(a[0]) = data[propId].value<QColor>(); - break; - case QVariant::Date: - *reinterpret_cast<QDate *>(a[0]) = data[propId].toDate(); - break; - default: - qFatal("Unknown type"); - break; + if (vTypes.testBit(propId)) { + if (c == QMetaObject::ReadProperty) { + *reinterpret_cast<QVariant *>(a[0]) = data[propId]; + } else if (c == QMetaObject::WriteProperty) { + needActivate = + (data[propId] != *reinterpret_cast<QVariant *>(a[0])); + data[propId] = *reinterpret_cast<QVariant *>(a[0]); } - } else if (c == QMetaObject::WriteProperty) { + } else { + if (c == QMetaObject::ReadProperty) { + switch(data[propId].type()) { + case QVariant::Int: + *reinterpret_cast<int *>(a[0]) = data[propId].toInt(); + break; + case QVariant::Bool: + *reinterpret_cast<bool *>(a[0]) = data[propId].toBool(); + break; + case QVariant::Double: + *reinterpret_cast<double *>(a[0]) = data[propId].toDouble(); + break; + case QVariant::String: + *reinterpret_cast<QString *>(a[0]) = data[propId].toString(); + break; + case QVariant::Color: + *reinterpret_cast<QColor *>(a[0]) = data[propId].value<QColor>(); + break; + case QVariant::Date: + *reinterpret_cast<QDate *>(a[0]) = data[propId].toDate(); + break; + default: + qFatal("Unknown type"); + break; + } + } else if (c == QMetaObject::WriteProperty) { - QVariant value = QVariant((QVariant::Type)data[propId].type(), a[0]); - needActivate = (data[propId] != value); - data[propId] = value; + QVariant value = QVariant((QVariant::Type)data[propId].type(), a[0]); + needActivate = (data[propId] != value); + data[propId] = value; + } } - } - if (c == QMetaObject::WriteProperty && needActivate) { - activate(object, baseSig + propId, 0); - } + if (c == QMetaObject::WriteProperty && needActivate) { + activate(object, baseSig + propId, 0); + } - return id; - } else { - return object->qt_metacall(c, id, a); + return id; + } + } else if(c == QMetaObject::InvokeMetaMethod) { + if(id >= baseSlot && id < (baseSlot + slotCount)) { + int idx = id - baseSlot + slotDataIdx; + QmlContext *ctxt = qmlContext(object); + QmlExpression expr(ctxt, slotData->at(idx), object); + expr.setTrackChange(false); + expr.value(); + return id; + } } + + return object->qt_metacall(c, id, a); } QT_END_NAMESPACE diff --git a/src/declarative/qml/qmlvmemetaobject_p.h b/src/declarative/qml/qmlvmemetaobject_p.h index 3fb1c46..d8ed242 100644 --- a/src/declarative/qml/qmlvmemetaobject_p.h +++ b/src/declarative/qml/qmlvmemetaobject_p.h @@ -52,7 +52,7 @@ class QmlRefCount; class QmlVMEMetaObject : public QAbstractDynamicMetaObject { public: - QmlVMEMetaObject(QObject *, const QMetaObject *, QmlRefCount * = 0); + QmlVMEMetaObject(QObject *, const QMetaObject *, QList<QString> *, int slotData, QmlRefCount * = 0); ~QmlVMEMetaObject(); protected: @@ -63,8 +63,12 @@ private: QmlRefCount *ref; int baseProp; int baseSig; + int baseSlot; + int slotCount; QVariant *data; QBitArray vTypes; + QList<QString> *slotData; + int slotDataIdx; }; QT_END_NAMESPACE diff --git a/src/declarative/util/qfxview.cpp b/src/declarative/util/qfxview.cpp index f71b87e..1315f19 100644 --- a/src/declarative/util/qfxview.cpp +++ b/src/declarative/util/qfxview.cpp @@ -348,7 +348,7 @@ void QFxView::continueExecute() } /*! \fn void QFxView::sceneResized(QSize size) - This signal is emitted when the view is resized. + This signal is emitted when the view is resized to \a size. */ /*! @@ -458,7 +458,8 @@ void QFxView::resizeEvent(QResizeEvent *e) } /*! \fn void QFxView::focusInEvent(QFocusEvent *e) - This virtual function does nothing in this class. + This virtual function does nothing with the event \a e + in this class. */ void QFxView::focusInEvent(QFocusEvent *) { @@ -467,7 +468,8 @@ void QFxView::focusInEvent(QFocusEvent *) /*! \fn void QFxView::focusOutEvent(QFocusEvent *e) - This virtual function does nothing in this class. + This virtual function does nothing with the event \a e + in this class. */ void QFxView::focusOutEvent(QFocusEvent *) { diff --git a/src/declarative/util/qmlanimation.cpp b/src/declarative/util/qmlanimation.cpp index 4b8ce4e..08a7a28 100644 --- a/src/declarative/util/qmlanimation.cpp +++ b/src/declarative/util/qmlanimation.cpp @@ -703,9 +703,10 @@ QColor QmlColorAnimation::from() const void QmlColorAnimation::setFrom(const QColor &f) { Q_D(QmlColorAnimation); - if (d->fromValue.isValid() && f == d->fromValue) + if (d->fromIsDefined && f == d->fromValue) return; d->fromValue = f; + d->fromIsDefined = f.isValid(); emit fromChanged(f); } @@ -726,9 +727,10 @@ QColor QmlColorAnimation::to() const void QmlColorAnimation::setTo(const QColor &t) { Q_D(QmlColorAnimation); - if (d->toValue.isValid() && t == d->toValue) + if (d->toIsDefined && t == d->toValue) return; d->toValue = t; + d->toIsDefined = t.isValid(); emit toChanged(t); } @@ -860,9 +862,13 @@ void QmlColorAnimation::transition(QmlStateActions &actions, (!target() || target() == obj)) { objs.insert(obj); Action myAction = action; - if (d->fromValue.isValid()) + + if (d->fromIsDefined) { myAction.fromValue = QVariant(d->fromValue); - if (d->toValue.isValid()) + } else { + myAction.fromValue = QVariant(); + } + if (d->toIsDefined) myAction.toValue = QVariant(d->toValue); modified << action.property; @@ -877,7 +883,7 @@ void QmlColorAnimation::transition(QmlStateActions &actions, Action myAction; myAction.property = QmlMetaProperty(obj, props.at(jj)); - if (d->fromValue.isValid()) + if (d->fromIsDefined) myAction.fromValue = QVariant(d->fromValue); myAction.toValue = QVariant(d->toValue); @@ -898,7 +904,7 @@ QVariantAnimation::Interpolator QmlColorAnimationPrivate::colorInterpolator = 0; void QmlColorAnimationPrivate::valueChanged(qreal v) { if (!fromSourced) { - if (!fromValue.isValid()) { + if (!fromIsDefined) { fromValue = qvariant_cast<QColor>(property.read()); } fromSourced = true; @@ -1993,9 +1999,10 @@ QVariant QmlVariantAnimation::from() const void QmlVariantAnimation::setFrom(const QVariant &f) { Q_D(QmlVariantAnimation); - if (d->from.isValid() && f == d->from) + if (d->fromIsDefined && f == d->from) return; d->from = f; + d->fromIsDefined = f.isValid(); emit fromChanged(f); } @@ -2017,9 +2024,10 @@ QVariant QmlVariantAnimation::to() const void QmlVariantAnimation::setTo(const QVariant &t) { Q_D(QmlVariantAnimation); - if (d->to.isValid() && t == d->to) + if (d->toIsDefined && t == d->to) return; d->to = t; + d->toIsDefined = t.isValid(); emit toChanged(t); } @@ -2109,7 +2117,7 @@ QList<QObject *> *QmlVariantAnimation::exclude() void QmlVariantAnimationPrivate::valueChanged(qreal r) { if (!fromSourced) { - if (!from.isValid()) { + if (!fromIsDefined) { from = property.read(); } fromSourced = true; @@ -2138,7 +2146,7 @@ void QmlVariantAnimation::prepare(QmlMetaProperty &p) d->property = d->userProperty; d->convertVariant(d->to, (QVariant::Type)d->property.propertyType()); - if (d->from.isValid()) + if (d->fromIsDefined) d->convertVariant(d->from, (QVariant::Type)d->property.propertyType()); d->fromSourced = false; @@ -2198,12 +2206,12 @@ void QmlVariantAnimation::transition(QmlStateActions &actions, objs.insert(obj); Action myAction = action; - if (d->from.isValid()) { + if (d->fromIsDefined) { myAction.fromValue = d->from; } else { myAction.fromValue = QVariant(); } - if (d->to.isValid()) + if (d->toIsDefined) myAction.toValue = d->to; d->convertVariant(myAction.fromValue, (QVariant::Type)myAction.property.propertyType()); @@ -2216,13 +2224,13 @@ void QmlVariantAnimation::transition(QmlStateActions &actions, } } - if (d->to.isValid() && target() && !objs.contains(target())) { + if (d->toIsDefined && target() && !objs.contains(target())) { QObject *obj = target(); for (int jj = 0; jj < props.count(); ++jj) { Action myAction; myAction.property = QmlMetaProperty(obj, props.at(jj)); - if (d->from.isValid()) { + if (d->fromIsDefined) { d->convertVariant(d->from, (QVariant::Type)myAction.property.propertyType()); myAction.fromValue = d->from; } diff --git a/src/declarative/util/qmlanimation_p.h b/src/declarative/util/qmlanimation_p.h index 4fcaa47..06b7c08 100644 --- a/src/declarative/util/qmlanimation_p.h +++ b/src/declarative/util/qmlanimation_p.h @@ -203,7 +203,8 @@ class QmlColorAnimationPrivate : public QmlAbstractAnimationPrivate Q_DECLARE_PUBLIC(QmlColorAnimation); public: QmlColorAnimationPrivate() - : QmlAbstractAnimationPrivate(), fromSourced(false), ca(0), value(this, &QmlColorAnimationPrivate::valueChanged) + : QmlAbstractAnimationPrivate(), fromSourced(false), fromIsDefined(false), toIsDefined(false), + ca(0), value(this, &QmlColorAnimationPrivate::valueChanged) { if (!colorInterpolator) colorInterpolator = QVariantAnimationPrivate::getInterpolator(QVariant::Color); @@ -213,11 +214,16 @@ public: QString easing; + QColor fromValue; + QColor toValue; + QList<QObject *> filter; QList<QObject *> exclude; + bool fromSourced; - QColor fromValue; - QColor toValue; + bool fromIsDefined; + bool toIsDefined; + QmlTimeLineValueAnimator *ca; virtual void valueChanged(qreal); @@ -350,7 +356,8 @@ class QmlVariantAnimationPrivate : public QmlAbstractAnimationPrivate Q_DECLARE_PUBLIC(QmlVariantAnimation); public: QmlVariantAnimationPrivate() - : QmlAbstractAnimationPrivate(), fromSourced(false), va(0), value(this, &QmlVariantAnimationPrivate::valueChanged) {} + : QmlAbstractAnimationPrivate(), fromSourced(false), fromIsDefined(false), toIsDefined(false), + va(0), value(this, &QmlVariantAnimationPrivate::valueChanged) {} void init(); @@ -364,6 +371,8 @@ public: QList<QObject *> exclude; bool fromSourced; + bool fromIsDefined; + bool toIsDefined; QmlTimeLineValueAnimator *va; virtual void valueChanged(qreal); diff --git a/src/script/qscriptextqobject.cpp b/src/script/qscriptextqobject.cpp index 4522807..802653a 100644 --- a/src/script/qscriptextqobject.cpp +++ b/src/script/qscriptextqobject.cpp @@ -736,7 +736,7 @@ static void callQtMethod(QScriptContextPrivate *context, QMetaMethod::MethodType meta->static_metacall(QMetaObject::CreateInstance, chosenIndex, params); } else { Q_ASSERT(thisQObject != 0); - thisQObject->qt_metacall(QMetaObject::InvokeMetaMethod, chosenIndex, params); + QMetaObject::metacall(thisQObject, QMetaObject::InvokeMetaMethod, chosenIndex, params); } if (scriptable) diff --git a/tools/qmlviewer/main.cpp b/tools/qmlviewer/main.cpp index c5676ab..26ff213 100644 --- a/tools/qmlviewer/main.cpp +++ b/tools/qmlviewer/main.cpp @@ -27,11 +27,15 @@ void usage() qWarning(" -v, -version ............................. display version"); qWarning(" -frameless ............................... run with no window frame"); qWarning(" -skin <qvfbskindir> ...................... run with a skin window frame"); - qWarning(" -recorddither ordered|threshold|floyd .... set dither mode used for recording"); + qWarning(" -recordfile <output> ..................... set output file"); + qWarning(" - ImageMagick 'convert' for GIF)"); + qWarning(" - png file for raw frames"); + qWarning(" - 'ffmpeg' for other formats"); + qWarning(" -recorddither ordered|threshold|floyd .... set GIF dither recording mode"); qWarning(" -recordperiod <milliseconds> ............. set time between recording frames"); - qWarning(" -autorecord [from-]<tomilliseconds> ...... set recording to start and stop automatically"); + qWarning(" -autorecord [from-]<tomilliseconds> ...... set recording to start and stop"); qWarning(" -devicekeys .............................. use numeric keys (see F1)"); - qWarning(" -cache ................................... enable a disk cache of remote content"); + qWarning(" -cache ................................... disk cache remote content"); qWarning(" -recordtest <directory> .................. record an autotest"); qWarning(" -runtest <directory> ..................... run a previously recorded test"); qWarning(" "); @@ -66,7 +70,8 @@ int main(int argc, char ** argv) int period = 0; int autorecord_from = 0; int autorecord_to = 0; - QString dither = "threshold"; + QString dither = "none"; + QString recordfile = "animation.gif"; QString skin; bool devkeys = false; bool cache = false; @@ -83,6 +88,10 @@ int main(int argc, char ** argv) cache = true; } else if (arg == "-recordperiod") { period = QString(argv[++i]).toInt(); + } else if (arg == "-recordfile") { + recordfile = QString(argv[++i]); + } else if (arg == "-recorddither") { + dither = QString(argv[++i]); } else if (arg == "-autorecord") { QString range = QString(argv[++i]); int dash = range.indexOf('-'); @@ -119,6 +128,7 @@ int main(int argc, char ** argv) QmlViewer viewer(testMode, testDir, 0, frameless ? Qt::FramelessWindowHint : Qt::Widget); viewer.setCacheEnabled(cache); viewer.openQml(fileName); + viewer.setRecordFile(recordfile); if (period>0) viewer.setRecordPeriod(period); if (autorecord_to) diff --git a/tools/qmlviewer/qmlviewer.cpp b/tools/qmlviewer/qmlviewer.cpp index 00cb7f1..094d779 100644 --- a/tools/qmlviewer/qmlviewer.cpp +++ b/tools/qmlviewer/qmlviewer.cpp @@ -35,7 +35,7 @@ #include <QMenu> QmlViewer::QmlViewer(QFxTestEngine::TestMode testMode, const QString &testDir, QWidget *parent, Qt::WindowFlags flags) - : QWidget(parent, flags) + : QWidget(parent, flags), frame_stream(0) { testEngine = 0; devicemode = false; @@ -218,6 +218,11 @@ void QmlViewer::setAutoRecord(int from, int to) } } +void QmlViewer::setRecordFile(const QString& f) +{ + record_file = f; +} + void QmlViewer::setRecordPeriod(int ms) { record_period = ms; @@ -246,7 +251,7 @@ void QmlViewer::keyPressEvent(QKeyEvent *event) exit(0); else if (event->key() == Qt::Key_F1 || (event->key() == Qt::Key_1 && devicemode)) { qDebug() << "F1 - help\n" - << "F2 - toggle GIF recording\n" + << "F2 - toggle video recording\n" << "F3 - take PNG snapshot\n" << "F4 - show items and state\n" << "F5 - reload QML\n" @@ -288,49 +293,95 @@ void QmlViewer::setRecording(bool on) if (on) { recordTimer.start(record_period,this); + QString fmt = record_file.right(4).toLower(); + if (fmt != ".png" && fmt != ".gif") { + // Stream video to ffmpeg + + QProcess *proc = new QProcess(this); + frame_stream = proc; + + QStringList args; + args << "-sameq"; // ie. high + args << "-y"; + args << "-r" << QString::number(1000/record_period); + args << "-f" << "rawvideo"; + args << "-pix_fmt" << "rgb32"; + args << "-s" << QString("%1x%2").arg(canvas->width()).arg(canvas->height()); + args << "-i" << "-"; + args << record_file; + proc->start("ffmpeg",args,QIODevice::WriteOnly); + } else { + // Store frames, save to GIF/PNG + frame_stream = 0; + } } else { recordTimer.stop(); - int frame=0; - QStringList inputs; - qDebug() << "Saving frames..."; - - foreach (QImage* img, frames) { - QString name; - name.sprintf("tmp-frame%04d.png",frame++); - if (record_dither=="ordered") - img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither|Qt::OrderedDither).save(name); - else if (record_dither=="threshold") - img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither|Qt::ThresholdDither).save(name); - else if (record_dither=="floyd") - img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither).save(name); - else - img->convertToFormat(QImage::Format_Indexed8).save(name); - inputs << name; - delete img; - } - QString output="animation.gif"; - - QStringList args; - - args << "-delay" << QString::number(record_period/10); - args << inputs; - args << output; - qDebug() << "Converting..." << output; - if (0!=QProcess::execute("convert", args)) { - qWarning() << "Cannot run ImageMagick 'convert' - not converted to gif"; - inputs.clear(); // don't remove them - qDebug() << "Wrote frames tmp-frame*.png"; + if (frame_stream) { + qDebug() << "Saving video..."; + frame_stream->close(); + qDebug() << "Wrote" << record_file; } else { - qDebug() << "Compressing..." << output; - if (0!=QProcess::execute("gifsicle", QStringList() << "-O2" << "-o" << output << output)) - qWarning() << "Cannot run 'gifsicle' - not compressed"; - qDebug() << "Wrote" << output; - } + int frame=0; + QStringList inputs; + qDebug() << "Saving frames..."; + + QString framename; + bool png_output = false; + if (record_file.right(4).toLower()==".png") { + if (record_file.contains('%')) + framename = record_file; + else + framename = record_file.left(record_file.length()-4)+"%04d"+record_file.right(4); + png_output = true; + } else { + framename = "tmp-frame%04d.png"; + png_output = false; + } + foreach (QImage* img, frames) { + QString name; + name.sprintf(framename.toLocal8Bit(),frame++); + if (record_dither=="ordered") + img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither|Qt::OrderedDither).save(name); + else if (record_dither=="threshold") + img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither|Qt::ThresholdDither).save(name); + else if (record_dither=="floyd") + img->convertToFormat(QImage::Format_Indexed8,Qt::PreferDither).save(name); + else + img->save(name); + inputs << name; + delete img; + } + + if (png_output) { + framename.replace(QRegExp("%\\d*."),"*"); + qDebug() << "Wrote frames" << framename; + inputs.clear(); // don't remove them + } else { + // ImageMagick and gifsicle for GIF encoding + QStringList args; + args << "-delay" << QString::number(record_period/10); + args << inputs; + args << record_file; + qDebug() << "Converting..." << record_file; + if (0!=QProcess::execute("convert", args)) { + qWarning() << "Cannot run ImageMagick 'convert' - recorded frames not converted"; + inputs.clear(); // don't remove them + qDebug() << "Wrote frames tmp-frame*.png"; + } else { + if (record_file.right(4).toLower() == ".gif") { + qDebug() << "Compressing..." << record_file; + if (0!=QProcess::execute("gifsicle", QStringList() << "-O2" << "-o" << record_file << record_file)) + qWarning() << "Cannot run 'gifsicle' - not compressed"; + } + qDebug() << "Wrote" << record_file; + } + } - foreach (QString name, inputs) - QFile::remove(name); + foreach (QString name, inputs) + QFile::remove(name); - frames.clear(); + frames.clear(); + } } qDebug() << "Recording: " << (recordTimer.isActive()?"ON":"OFF"); } @@ -338,7 +389,12 @@ void QmlViewer::setRecording(bool on) void QmlViewer::timerEvent(QTimerEvent *event) { if (event->timerId() == recordTimer.timerId()) { - frames.append(new QImage(canvas->asImage())); + if (frame_stream) { + QImage frame(canvas->asImage()); + frame_stream->write((char*)frame.bits(),frame.numBytes()); + } else { + frames.append(new QImage(canvas->asImage())); + } if (record_autotime && autoTimer.elapsed() >= record_autotime) setRecording(false); } else if (event->timerId() == autoStartTimer.timerId()) { diff --git a/tools/qmlviewer/qmlviewer.h b/tools/qmlviewer/qmlviewer.h index 0fa879d..fc65ebf 100644 --- a/tools/qmlviewer/qmlviewer.h +++ b/tools/qmlviewer/qmlviewer.h @@ -33,6 +33,7 @@ public: void setRecordDither(const QString& s) { record_dither = s; } void setRecordPeriod(int ms); + void setRecordFile(const QString&); int recordPeriod() const { return record_period; } void setRecording(bool on); bool isRecording() const { return recordTimer.isActive(); } @@ -59,9 +60,11 @@ private: void init(QFxTestEngine::TestMode, const QString &, const QString& fileName); QBasicTimer recordTimer; QList<QImage*> frames; + QIODevice* frame_stream; QBasicTimer autoStartTimer; QTime autoTimer; QString record_dither; + QString record_file; int record_period; int record_autotime; bool devicemode; diff --git a/tools/tools.pro b/tools/tools.pro index 2c83580..2ff0214 100644 --- a/tools/tools.pro +++ b/tools/tools.pro @@ -24,7 +24,7 @@ mac { SUBDIRS += kmap2qmap -contains(QT_CONFIG, declarative):SUBDIRS += qmlviewer qmlconv +contains(QT_CONFIG, declarative):SUBDIRS += qmlviewer contains(QT_CONFIG, dbus):SUBDIRS += qdbus !wince*:contains(QT_CONFIG, xmlpatterns): SUBDIRS += xmlpatterns embedded: SUBDIRS += makeqpf |