Viadeo Twitter Google Bookmarks ! Facebook Digg del.icio.us MySpace Yahoo MyWeb Blinklist Netvouz Reddit Simpy StumbleUpon Bookmarks Windows Live Favorites 
Logo Documentation Qt ·  Page d'accueil  ·  Toutes les classes  ·  Toutes les fonctions  ·  Vues d'ensemble  · 

QExpressionEvaluator Class Reference
[QtBaseModule]

The QExpressionEvaluator class computes the results of arithmetic, logical and string based expressions. More...

    #include <QExpressionEvaluator>

Inherits QObject.

Public Types

Public Functions

  • 29 public functions inherited from QObject

Public Slots

  • 1 public slot inherited from QObject

Signals

Additional Inherited Members

  • 1 property inherited from QObject
  • 1 public type inherited from QObject
  • 4 static public members inherited from QObject
  • 7 protected functions inherited from QObject
  • 2 protected variables inherited from QObject

Detailed Description

The QExpressionEvaluator class computes the results of arithmetic, logical and string based expressions.

Most interestingly, the expression evaluator has the ability to use values from the Qt Extended valuespace in its expressions and signal when the resulting expression changes through termsChanged().

Overview

It takes as input through setExpression() an expression such as "2 + 2" and calculates the result.

Here is an example of basic usage of the expression evaluator.

    QExpressionEvaluator ee;
    ee.setExpression("2 + 2");
    if(!ee.isValid()) { // check if syntax/semantics correct.
        qWarning("Syntax or semantic error in expression.");
    } else {
        if(!ee.evaluate()) { // evaluate the expression
            qWarning("Run-time error when evaluating expression"); // run-time error - type coercion or divide by zero.
        } else {
            QVariant result = ee.result();  // retrieve the result
            int x = result.toInt(); // x == 4
        }
    }

Details

The expression evaluator functionally operates in 2 phases. The first phase is the setup phase, where the specified expression is tokenized, parsed, semantically checked and byte code generated. The isValid() function returns whether this entire setup phase is successful ie. the specified expression is syntactually and semantically valid.

The second phase is the evaluation phase, where the generated bytecode from the first phase is executed to compute the result of the expression. The evaluate() function uses a virtual machine to execute the bytecode and store the resulting value. Run-time errors occur when an expression attempts to divide-by-zero or if an expression evaluator term cannot be coerced to a required type. The return value of evaluate() indicates whether there were any run-time errors. If evaluate() returns true, result() can then be called to retreive the calcuated result of the expression as a QVariant. You should cast the variant to the data type you expect.

Supported Data Types

The expression evaluator supports 5 data types: int, real, string and bool. real numbers are represented either using the C++ double data type, or by using fixed point calculations. C++ double is the default, but you probably want to use the fixed point format for user visible applications of the expression evaluator, such as a desktop calculator. This can be set using the setFloatingPointFormat() function.

Supported Operators

Table is in highest to lowest precedence.

OperatorDescription
( ) - !Brackets to control evaluation order of expression, unary minus, logical negation. eg. "2 * (3 + 4)" "-20" "!false"
* / %Arithmetic multiplication, division and modulus. eg. "2 * 3 / 3 % 3"
+ - .Arithmetic addition and subtraction. String concatenation. eg. "2 + 3 - 4" ""hello" . "world""
< > <= >=Logical comparison. eg "10.9 > = 10.8"
== !=Logical equality. eg. "true != false"
&&Logical AND eg. "true && true"
||Logical OR eg. "false || true"

Type Conversion

Operators in the expression evaluator work with operands of the same type ie. the '+' operator can only add two integer or two real numbers. However, a user may still mix data types and the operands will be coerced to the correct type for the operator.

Consider the expression: 2 + "2"

The '+' operator adds two number operands, but the RHS operand is a string. As the LHS is an integer, the expression evaluator tries to coerce the RHS string to an integer to meet the requirements of the '+' operator. In this case, the coercion would succeed and "2" would simply become an integer 2. The result of the expression would then be the integer 4.

If operands cannot be coerced to the required types for an operator, then for static coercion the setup phase fails and isValid() returns false and for run-time coercion evaluate() returns false.

Run-time coercion failures can occur for 2 reasons:

a term, eg. a key in the valuespace, does not return a value that can be coerced to the required type, or a return value of one side of the expression cannot be coerced to the required type. eg. 2 + ("2" . "@/value/in/valuespace") would fail at run-time because the RHS of '+' is a string, calculated at runtime, that cannot be coerced to an integer.

Below are the data type requirements of the expression evaluator's operators.

OperatorRequired operand typesReturn type
Basic arithmetic (* / + -)Alteast 1 double or integer./ always returns a real, others return real or integer depending on operands.
Modulus (%)Two integers.integer
String Concatentation (.)Atleast 1 string.string
Logical Comparison (< > <= >=)Atleast 1 double, integer or bool.bool
Other Logical (== != && || !)All types.bool

Valuespace integration

The expression evaluator has the ability to use values from the Qt Extended valuespace in its expressions.

    2 + @/Value/Space/Key

The above code would add 2 and the value for /Value/Space/Key in the valuespace.

The '@' character uniquely identifies the subsequent characters as a valuespace key to the expression evaluator.

In the above example, /Value/Space/Key must return data that can be converted to an integer. If conversion fails, a run-time error will occur and evaluate() will return false.

If a value in the valuespace changes, expressions which use that value will emit the termsChanged() signal.


Member Type Documentation

enum QExpressionEvaluator::FloatingPointFormat

Controls the floating point format used by the expression evaluator.

ConstantValueDescription
QExpressionEvaluator::Double0C++ double data type.
QExpressionEvaluator::FixedPoint1Fixed point arithmetic using an 8byte integer.


Member Function Documentation

QExpressionEvaluator::QExpressionEvaluator ( QObject * parent = 0 )

Constructs a QExpressionEvaluator. parent is passed to the QObject constructor.

QExpressionEvaluator::QExpressionEvaluator ( const QByteArray & expr, QObject * parent = 0 )

Constructs a QExpressionEvaluator.

expr is passed to setExpression(). parent is passed to the QObject constructor.

QExpressionEvaluator::~QExpressionEvaluator ()

Destroys the QExpressionEvaluator.

void QExpressionEvaluator::clear ()   [slot]

Clears the set expression and any associated data structures.

The expression becomes invalid ie. isValid() returns false.

bool QExpressionEvaluator::evaluate ()

Evaluates the expression specified through setExpression().

isValid() must return true before you call this function, otherwise it will abort().

Returns true if the expression was successfully evaluated, or false if a run-time error occured.

A run-time error can occur due to a coercion error or divide by zero.

If this function returns true, the result of the evaluation can be retrieved using result().

QByteArray QExpressionEvaluator::expression () const

Returns the current expression data the evaluator is operating on.

See also setExpression().

FloatingPointFormat QExpressionEvaluator::floatingPointFormat () const

Returns the current floating point format.

See also setFloatingPointFormat().

bool QExpressionEvaluator::isValid () const

Returns true if this expression is valid, otherwise false.

An expression is valid if it is not empty, it is syntactually and semantically correct, and a previous call to evaluate() did not result in a run-time error.

You must not call evaluate() unless this function returns true.

QVariant QExpressionEvaluator::result ()

Returns the result of the last call to evaluate() as a QVariant.

Returns an empty QVariant if evaluate() has not yet been called.

bool QExpressionEvaluator::setExpression ( const QByteArray & expr )   [slot]

Sets the expression for the evaluator to be expr

expr is parsed and semantically checked immediat

Returns true on success; otherwise returns false.

You should call isValid() after this function to determine whether the setup phase was completed successfully.

See also expression().

void QExpressionEvaluator::setFloatingPointFormat ( const FloatingPointFormat & fmt )

Sets the floating point format to be used by the expression evaluator to fmt.

The default is QExpressionEvaluator::Double, but setting QExpressionEvaluator::FixedPoint may give results appropriate for user level applications.

See also floatingPointFormat().

void QExpressionEvaluator::termsChanged ()   [signal]

Emitted when a pluggable term in the expression changes.

Publicité

Best Of

Actualités les plus lues

Semaine
Mois
Année
  1. « Quelque chose ne va vraiment pas avec les développeurs "modernes" », un développeur à "l'ancienne" critique la multiplication des bibliothèques 94
  2. Apercevoir la troisième dimension ou l'utilisation multithreadée d'OpenGL dans Qt, un article des Qt Quarterly traduit par Guillaume Belz 0
  3. Les développeurs ignorent-ils trop les failles découvertes dans leur code ? Prenez-vous en compte les remarques des autres ? 17
  4. Pourquoi les programmeurs sont-ils moins payés que les gestionnaires de programmes ? Manquent-ils de pouvoir de négociation ? 42
  5. Quelles nouveautés de C++11 Visual C++ doit-il rapidement intégrer ? Donnez-nous votre avis 10
  6. Adieu qmake, bienvenue qbs : Qt Building Suite, un outil déclaratif et extensible pour la compilation de projets Qt 17
  7. 2017 : un quinquennat pour une nouvelle version du C++ ? Possible, selon Herb Sutter 9
Page suivante

Le Qt Labs au hasard

Logo

Velours et QML Scene Graph

Les Qt Labs sont les laboratoires des développeurs de Qt, où ils peuvent partager des impressions sur le framework, son utilisation, ce que pourrait être son futur. Lire l'article.

Communauté

Ressources

Liens utiles

Contact

  • Vous souhaitez rejoindre la rédaction ou proposer un tutoriel, une traduction, une question... ? Postez dans le forum Contribuez ou contactez-nous par MP ou par email (voir en bas de page).

Qt dans le magazine

Cette page est une traduction d'une page de la documentation de Qt, écrite par Nokia Corporation and/or its subsidiary(-ies). Les éventuels problèmes résultant d'une mauvaise traduction ne sont pas imputables à Nokia. Qt qtextended4.4
Copyright © 2012 Developpez LLC. Tous droits réservés Developpez LLC. Aucune reproduction, même partielle, ne peut être faite de ce site et de l'ensemble de son contenu : textes, documents et images sans l'autorisation expresse de Developpez LLC. Sinon, vous encourez selon la loi jusqu'à 3 ans de prison et jusqu'à 300 000 E de dommages et intérêts. Cette page est déposée à la SACD.
Vous avez déniché une erreur ? Un bug ? Une redirection cassée ? Ou tout autre problème, quel qu'il soit ? Ou bien vous désirez participer à ce projet de traduction ? N'hésitez pas à nous contacter ou par MP !
 
 
 
 
Partenaires

Hébergement Web