Data Bindings

Been having some fun this week trying to add support for data bindings to Qt Script, and now I have something that seems to work. This code shows the basic usage:

QScriptEngine engine;
QPushButton button;
QScriptValue scriptButton = engine.newQObject(&button);
engine.evaluate("x = 'foo'");
scriptButton.setProperty("text", "x", QScriptValue::DataBinding);

This will cause the button's text property to be updated whenever the script variable x changes, either from C++ (QScriptValue::setProperty()) or from
script. QObject properties can be part of the binding expression as well, as long as the NOTIFY attribute is specified in the Q_PROPERTY definition. Qt Script will discover that the property has a signal associated with it and use it to track changes. Qt's classes already use NOTIFY for some properties (e.g. QLabel::text).

Below is a small example. The text property of a label is bound to the text property of a lineedit and the script variable verb; the final value is made by concatenating the lineedit's text, the verb and a string literal.

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

QWidget win;
QVBoxLayout *vbox = new QVBoxLayout(&win);
QLineEdit *lineEdit = new QLineEdit();
QLabel *label = new QLabel();
label->setStyleSheet("font-size: 24px");

QScriptEngine engine;
QScriptEngineDebugger debugger;

QScriptValue scriptLineEdit = engine.newQObject(lineEdit);
engine.globalObject().setProperty("lineEdit", scriptLineEdit);
QScriptValue scriptLabel = engine.newQObject(label);
engine.globalObject().setProperty("label", scriptLabel);

engine.evaluate("verb = 'smack'");
scriptLabel.setProperty("text", "lineEdit.text + ' ' + verb + 's you!'", QScriptValue::DataBinding);;

return app.exec();

The result, after typing something into the lineedit and assigning something to verb:

Qt Script data binding example

I've also added an extension to QScriptClass that enables you to send property change notifications for custom (non-QObject-based) script objects, i.e. you can use your own notify mechanism.

As I said, this isn't in Qt yet, it's just an experiment, but it's looking pretty interesting.

Blog Topics: