Home · Tutorial · Classes · Functions · Language · QSA Workbench · Qt Documentation · www.trolltech.com

Scriptbutton Example

The Scriptbutton example demonstrates how to implement a GUI control with a customizable action on activation. ScriptButton is a specialized QPushButton class that can have a snippet of script code attached to it. The script will be executed whenever the user clicks on the button. To modify the behavior of the buttons, the user can right-click a button and choose to either rename the button label or edit the script code in a simple editor.

The Scriptbutton example also shows how to extend the scripting API of an existing C++ QObject class, which in this case is QWidget. Here we extend every QWidget class by two scripting functions: sendMousePressEvent() and sendMouseReleaseEvent(). These functions will show up in the API of every QWidget subclass and will then allow the scriptwriter to send mouse press and release events to any QWidget.

For demonstration purposes, the example widget contains both a QLCDNumber and QLineEdit widget with properties that can be changed by the buttons located on the right side of the dialog.

Implementing Scriptbutton

The scriptbutton is a QPushButton subclass and contains an extra property which stores the code that will be executed when clicking the button. To edit the code, a subclass of QSEditor is used. The scriptbutton's code is passed into a call to QSInterpreter::evaluate() in the scriptbutton's executeScript() slot, which is connected to its clicked() signal.

Implementation of the QWidget Extension

To extend the QWidget API for the script writer, we implement a class WidgetWrapper which inherits QObject and takes the widget it wraps in its constructor. WidgetWrapper then implements the two slots sendMousePressEvent() and sendMouseReleaseEvent() which send a mouse event to the wrapped widget.

To make this wrapper known to the Qt Script Interpreter, we implement a WidgetWrapperFactory which inherits QSWrapperFactory. This enables the Qt Script Interpreter to create a WidgetWrapper for every QWidget it exposes to Qt Script.

Copyright © 2006 Trolltech Trademarks
QSA 1.2.2