Qt Reference Documentation

Contents

Qt Script Tetrix Example

Files:

The QSTetrix example is a Qt Script version of the classic Tetrix game.

Overview

The program logic in this example is a fairly straight port of the logic in the C++ Tetrix Example. You may find it useful to compare the implementations of the TetrixBoard, TetrixPiece and TetrixWindow classes to see how Qt Script is used to implement methods, call Qt functions, and emit signals.

Setting up the GUI

The graphical user interface is defined in a UI file, created using Qt Designer, and is set up in the example's C++ main.cpp file.

 class TetrixUiLoader : public QUiLoader
 {
 public:
     TetrixUiLoader(QObject *parent = 0)
         : QUiLoader(parent)
         { }
     virtual QWidget *createWidget(const QString &className, QWidget *parent = 0,
                                   const QString &name = QString())
     {
         if (className == QLatin1String("TetrixBoard")) {
             QWidget *board = new TetrixBoard(parent);
             board->setObjectName(name);
             return board;
         }
         return QUiLoader::createWidget(className, parent, name);
     }
 };

We define a custom UI loader that handles our TetrixBoard widget; this is the main component of the UI (where the pieces are drawn).

     QApplication app(argc, argv);
     QScriptEngine engine;

     QScriptValue Qt = engine.newQMetaObject(QtMetaObject::get());
     Qt.setProperty("App", engine.newQObject(&app));
     engine.globalObject().setProperty("Qt", Qt);

We initialize the script engine to have the Qt namespace, so that e.g., Qt.Key_Left will be available to script code. We also make the application object available (for the quit() slot).

     evaluateFile(engine, ":/tetrixpiece.js");
     evaluateFile(engine, ":/tetrixboard.js");
     evaluateFile(engine, ":/tetrixwindow.js");

Several scripts are evaluated as part of the engine setup process. The tetrixpiece.js file contains the definition of the TetrixPiece class, which is used to populate the play field. The tetrixboard.js file contains the definition of the TetrixBoard class, which contains the main game logic. Finally, tetrixwindow.js contains the definition of the TetrixWindow class, which wires up the top-level widget.

     TetrixUiLoader loader;
     QFile uiFile(":/tetrixwindow.ui");
     uiFile.open(QIODevice::ReadOnly);
     QWidget *ui = loader.load(&uiFile);
     uiFile.close();

     QScriptValue ctor = engine.evaluate("TetrixWindow");
     QScriptValue scriptUi = engine.newQObject(ui, QScriptEngine::ScriptOwnership);
     QScriptValue tetrix = ctor.construct(QScriptValueList() << scriptUi);

A form is created from the UI file. A new TetrixWindow script object is then constructed, passing the form as its argument.

     ui->resize(550, 370);
     ui->show();

     qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
     return app.exec();

The form is shown, and the event loop is entered.