Qt Jambi is the Java edition of the Qt application development framework. At the heart of Qt Jambi are the C++ libraries that form Qt, made available to Java programmers through the Java Native Interface (JNI). Although considerable effort has gone into making Qt Jambi integrate smoothly with Java and to make its API natural to use for Java programmers, C++/Qt programmers will still find the API familiar and predictable. All the classes are documented using Javadoc at http://doc.trolltech.com/qtjambi/
.
Until now, Java GUI programmers have had to make do with AWT, Swing, SWT, and similar GUI class libraries, none of which are as convenient to use or as powerful as Qt. For example, in the traditional Java GUI libraries, connecting a user action, such as clicking a button, to a corresponding method involves writing an event listener class; in Qt Jambi, only one line of code is required to achieve the same thing. And Qt’s layout managers are much easier to use than Swing’s BoxLayout
and GridBagLayout
, and they produce better-looking results.
Qt Jambi applications can have main windows with menu bars, toolbars, dock windows, and a status bar, just like Qt applications written in C++. They also have the native look and feel of the platform they are running on, and they respect the user’s preferences regarding themes, colors, fonts, and so on. With the full power of Qt under the hood, Qt Jambi applications can take advantage of Qt’s powerful 2D graphics architecture (notably the graphics view framework) and of extensions such as OpenGL.
The benefits of Qt Jambi are not limited to Java programmers. In particular, C++ programmers can make their custom Qt components available to Java programmers using the same generator tool that Trolltech uses to make the Qt API available in Qt Jambi.
In this appendix, we will show how Java programmers can start using Qt Jambi to create GUI applications. Then we will show how to make use of Qt Jambi in Eclipse, which integrates Qt Designer, and finally we will show how to make custom C++ components available to Qt Jambi programmers. This appendix assumes that you are familiar with C++/Qt programming and with Java. Qt Jambi requires Java 1.5 or later.
In this section, we will develop a small Java application that presents the window shown in Figure C.1. Apart from its window title, the Jambi Find dialog has the same appearance and behavior as the Find dialog we created back in Chapter 2. By reusing the same example, we can more easily see the differences and similarities between C++/Qt and Qt Jambi programming. While reviewing the code, we will discuss the conceptual differences between C++ and Java as they arise.
The implementation of the Jambi Find application is done in a single file called FindDialog.java
. We will review the contents of this file piece by piece, starting with the import
declarations.
import com.trolltech.qt.core.*; import com.trolltech.qt.gui.*;
Between them, these two import
declarations make all of Qt’s core and GUI classes available to Java. Additional sets of classes can be made available with similar import
declarations (e.g., import com.trolltech.qt.opengl.*
).
public class FindDialog extends QDialog {
The FindDialog
class is a subclass of QDialog
, like in the C++ version of the example. In C++, we declare signals in the header file, relying on the moc
tool to generate the supporting code. In Qt Jambi, Java’s introspection facilities are used to implement the signals and slots mechanism. But we still need some means of declaring signals, and this is done using the Signal
N
classes:
public Signal2<String, Qt.CaseSensitivity> findNext = new Signal2<String, Qt.CaseSensitivity>(); public Signal2<String, Qt.CaseSensitivity> findPrevious = new Signal2<String, Qt.CaseSensitivity>();
There are ten Signal
N
classes—Signal0
, Signal1<T1>
, ..., Signal9<T1,
...,T9>
. The numbers in their names indicate how many arguments they take, and the types T1
, ..., T9
specify the types of the arguments. Here, we have declared two signals, each taking two arguments. In both cases, the first argument is a Java String
, and the second argument is of type Qt.CaseSensitivity
, a Java enum type. Wherever a QString
is needed in the Qt API, in Qt Jambi we use a String
instead.
Unlike the other Signal
N
classes, Signal0
is not a generic class. To create a signal with no arguments, we use Signal0
like this:
public Signal0 somethingHappened = new Signal0();
Having created the signals we need, we are now ready to see the implementation of the constructor. The method is quite long, so we will look at it in three parts.
public FindDialog(QWidget parent) { super(parent); label = new QLabel(tr("Find &what:")); lineEdit = new QLineEdit(); label.setBuddy(lineEdit); caseCheckBox = new QCheckBox(tr("Match &case")); backwardCheckBox = new QCheckBox(tr("Search &backward")); findButton = new QPushButton(tr("&Find")); findButton.setDefault(true); findButton.setEnabled(false); closeButton = new QPushButton(tr("Close"));
The only differences between creating the widgets in Java compared to C++ are the small details of syntax. Note that tr()
returns a String
, not a QString
.
lineEdit.textChanged.connect(this, "enableFindButton(String)"); findButton.clicked.connect(this, "findClicked()"); closeButton.clicked.connect(this, "reject()");
The syntax for signal–slot connections in Qt Jambi is somewhat different than in C++/Qt, but it is still short and simple. In general, the syntax is
sender.signalName.connect(receiver, "slotName(T1, ..., TN)");
Unlike in C++/Qt, we don’t need to specify a signature for the signal. If a signal has more parameters than the slots it connects to, the additional parameters are ignored. Furthermore, in Qt Jambi, the signal–slot mechanism is not limited to QObject
subclasses: Any class that inherits QSignalEmitter
can emit signals, and any method of any class can be a slot.
QHBoxLayout topLeftLayout = new QHBoxLayout(); topLeftLayout.addWidget(label); topLeftLayout.addWidget(lineEdit); QVBoxLayout leftLayout = new QVBoxLayout(); leftLayout.addLayout(topLeftLayout); leftLayout.addWidget(caseCheckBox); leftLayout.addWidget(backwardCheckBox); QVBoxLayout rightLayout = new QVBoxLayout(); rightLayout.addWidget(findButton); rightLayout.addWidget(closeButton); rightLayout.addStretch(); QHBoxLayout mainLayout = new QHBoxLayout(); mainLayout.addLayout(leftLayout); mainLayout.addLayout(rightLayout); setLayout(mainLayout); setWindowTitle(tr("Jambi Find")); setFixedHeight(sizeHint().height()); }
The layout code is practically identical to the C++ original, with the same layout classes working in exactly the same way. Qt Jambi can also use forms created with Qt Designer, using juic
(the Java user interface compiler), as we will see in the next section.
private void findClicked() { String text = lineEdit.text(); Qt.CaseSensitivity cs = caseCheckBox.isChecked() ? Qt.CaseSensitivity.CaseSensitive : Qt.CaseSensitivity.CaseInsensitive; if (backwardCheckBox.isChecked()) { findPrevious.emit(text, cs); } else { findNext.emit(text, cs); } }
The Java syntax for referring to enum values is a bit more verbose than in C++, but it is easy to understand. To emit a signal, we call the emit()
method on a Signal
N
object, passing arguments of the correct types. The type-checking is done when the program is compiled.
private void enableFindButton(String text) { findButton.setEnabled(text.length() == 0); }
The enableFindButton()
method is essentially the same as the C++ original.
private QLabel label; private QLineEdit lineEdit; private QCheckBox caseCheckBox; private QCheckBox backwardCheckBox; private QPushButton findButton; private QPushButton closeButton;
In keeping with the code in the rest of the book, we have declared all the widgets as private fields of the class. This is purely a matter of style; nothing is stopping us from declaring in the constructor itself those widgets that are referred to only in the constructor. For example, we could have declared label
and closeButton
in the constructor since they are not referred to anywhere else, and they would not be garbage-collected when the constructor finishes. This works because Qt Jambi uses the same parent–child ownership mechanism as C++/Qt, so once the label
and closeButton
are laid out, the FindDialog
form takes ownership of them, and behind the scenes it keeps a reference to them to keep them alive. Qt Jambi deletes child widgets recursively, so if a top-level window is deleted, the window in turn deletes all its child widgets and layouts, which delete theirs, and so on, until cleanup is complete.
Qt Jambi makes full use of Java’s garbage-collection functionality, so unlike AWT, Swing, and SWT, if the last reference to a top-level window is deleted, the window will be scheduled for garbage collection, and no explicit call to dispose()
is necessary. This approach is very convenient and works the same as in C++/Qt. The main caveat is that for SDI (single document interface) applications, we must keep a reference to each top-level window that is created, to prevent them from being garbage-collected. (In C++/Qt, SDI applications normally use the Qt::WA_DeleteOnClose
attribute to prevent memory leaks.)
public static void main(String[] args) { QApplication.initialize(args); FindDialog dialog = new FindDialog(null); dialog.show(); QApplication.exec(); } }
For convenience, we have provided the FindDialog
with a main()
method that instantiates a dialog and pops it up. The import com.trolltech.qt.gui.*
declaration ensures that a static QApplication
object is available. When a Qt Jambi application starts, we must call QApplication.initialize()
and pass it the command-line arguments. This allows the QApplication
object to handle the arguments it recognizes, such as -font
and -style
.
When we create the FindDialog
, we pass null
as parent to signify that the dialog is a top-level window. Once the main()
method is finished, the dialog will go out of scope and be garbage-collected. The call to QApplication.exec()
starts off the event loop, and returns control to the main()
method only when the user closes the dialog.
The Qt Jambi API is very similar to the C++/Qt API, but there are some differences. For example, in C++, the QWidget::mapTo()
member function has the following signature:
QPoint mapTo(QWidget *widget, const QPoint &point) const;
The QWidget
is passed as a non-const pointer, whereas the QPoint
is passed as a const reference. In Qt Jambi, the equivalent method has the signature
public final QPoint mapTo(QWidget widget, QPoint point) { ... }
Because Java does not have pointers, there is no visual distinction in method signatures to indicate whether an object passed to a method can be modified by the method. In theory, the mapTo()
method could alter either parameter since they are both references, but Qt Jambi promises not to alter the QPoint
argument, since in C++ it is passed as a constant reference. From the context, it is usually clear which parameters are alterable and which are not. In case of doubt, we can refer to the documentation to clarify the situation.
In addition to not altering arguments that are passed by value or as constant references in C++, Qt Jambi also promises that the return value of any non-void
method, which in C++ would be returned as a value or as a constant reference, is an independent copy, so altering it will not lead to any side effects.
We mentioned earlier that in Qt Jambi, wherever a QString
would be used in C++/Qt, a Java String
is used instead. This kind of correspondence also applies to the QChar
class, which has two Java equivalents: char
and java.lang.Character
. There are similar correspondences regarding some of Qt’s container classes: QHash
is replaced by java.util.HashMap
, QList
and QVector
by java.util.List
, and QMap
by java.util.SortedMap
. In addition, QThread
is replaced by java.lang.Thread
.
The Qt model/view architecture and the database API make extensive use of QVariant
. Such a type isn’t needed in Java because all Java objects have java.lang.Object
as an ancestor, so throughout Qt Jambi’s API, QVariant
is replaced by java.lang.Object
. The extra methods that QVariant
provides are available as static methods in com.trolltech.qt.QVariant
.
We have now finished reviewing a small Qt Jambi application, and we discussed many of the conceptual differences between Qt Jambi and C++/Qt programming. Building and running a Qt Jambi application is no different from any other Java application, except that the CLASSPATH
environment variable must specify the directory where Qt Jambi is installed. We must compile the class using a Java compiler and then we can execute the class using a Java interpreter. For example:
export CLASSPATH=$CLASSPATH:$HOME/qtjambi/qtjambi.jar:$PWD javac FindDialog.java java FindDialog
Here we have used the Bash shell to set the CLASSPATH
environment variable; other command-line interpreters may require a different syntax. We include the current directory in the CLASSPATH
so that the FindDialog
class itself can be found. On Mac OS X, the command-line option -XstartOnFirstThread
must be supplied to java
to address a threading issue with Apple’s Java virtual machine. On Windows, we execute the application like this:
set CLASSPATH=%CLASSPATH%;%JAMBIPATH%qtjambi.jar;%CD% javac FindDialog.java java FindDialog
Qt Jambi can also be used within an IDE. In the next section, we will look at how to edit, build, and test a Qt Jambi application using the popular Eclipse IDE.
The Eclipse IDE (“Eclipse” for short) is one of the key pieces of software in the Eclipse family of more than sixty open source projects. Eclipse is very popular with Java programmers, and since it is written in Java, it runs on all major platforms. Eclipse displays a collection of panels, called views. Many views are available in Eclipse, including navigator, outline, and editor views, and each particular collection of views is called a perspective.
To make Qt Jambi and Qt Designer available inside Eclipse, it is necessary to install the Qt Jambi Eclipse integration package. Once the package is unpacked in the right location, Eclipse must be run with the -clean
option to force it to look for new plugins, rather than relying on its cache. The Preferences dialog will now have an extra option called “Qt Jambi Preference Page”. It is necessary to go to this page and set Qt Jambi’s location, as explained in http://doc.trolltech.com/qtjambi-4.3.2_01/com/trolltech/qt/qtjambi-eclipse.html
. Once the path has been set and verified, Eclipse should be closed and restarted for the changes to take effect.
The next time we start Eclipse and click File|New Project, the New Project dialog that pops up will offer two kinds of Qt Jambi project: Qt Jambi Project and Qt Jambi Project (Using Designer Form). In this section, we will discuss both of these project types by presenting a Qt Jambi version of the Go to Cell example developed in Chapter 2.
To create a Qt Jambi application purely in code, click File|New Project, choose “Qt Jambi Project”, and go through each page of the wizard. At the end, Eclipse will create a project with a skeleton .java
file with a main()
method and a constructor. The application can be run from within Eclipse using the Run|Run menu option. Eclipse shows syntax errors in the left margin of the editor, and shows any errors that occur at run-time in a console window.
Creating a Qt Jambi application that uses Qt Designer is very similar to creating a pure code application. Click File|New Project, and then choose “Qt Jambi Project (Using Designer Form)”. Again, a wizard will appear. Call the project “JambiGoToCell”, and on the last page, specify “GoToCellDialog” as the class name and choose “Dialog” as the form type.
Once the wizard has finished, it will have created GoToCellDialog.java
and also a Java user interface file GoToCellDialog.jui
. Double-click the .jui
file to make the Qt Designer editor visible. A form with OK and Cancel buttons will be shown. To access Qt Designer’s functionality, click Window|Open Perspective|Other, then double-click Qt Designer UI. This perspective shows Qt Designer’s signal–slot editor, action editor, property editor, widget box, and more, as shown in Figure C.2.
To complete the design, we perform the same steps as in Chapter 2 (p. 24). The dialog can be previewed as it could be within Qt Designer, and since Eclipse generates skeleton code it is also possible to run it by clicking Run|Run.
The final stage is to edit the GoToCellDialog.java
file to implement the functionality we need. Two constructors are generated by Eclipse, but we only want one of them, so we delete the parameterless constructor. In the generated main()
method, we must pass null
as the parent to the GoToCellDialog
constructor. Also, we must implement the GoToCellDialog(QWidget parent)
constructor, and provide a on_lineEdit_textChanged(String)
method that is called whenever the line editor’s textChanged()
signal is emitted. Here is the resulting GoToCellDialog.java
file:
import com.trolltech.qt.core.*; import com.trolltech.qt.gui.*; public class GoToCellDialog extends QDialog { private Ui_GoToCellDialogClass ui = new Ui_GoToCellDialogClass(); public GoToCellDialog(QWidget parent) { super(parent); ui.setupUi(this); ui.okButton.setEnabled(false); QRegExp regExp = new QRegExp("[A-Za-z][1-9][0-9]{0,2}"); ui.lineEdit.setValidator(new QRegExpValidator(regExp, this)); ui.okButton.clicked.connect(this, "accept()"); ui.cancelButton.clicked.connect(this, "reject()"); } private void on_lineEdit_textChanged(String text) { ui.okButton.setEnabled(!text.isEmpty()); } public static void main(String[] args) { QApplication.initialize(args); GoToCellDialog testGoToCellDialog = new GoToCellDialog(null); testGoToCellDialog.show(); QApplication.exec(); } }
Eclipse takes care of invoking juic
to convert GoToCellDialog.jui
into Ui_GoTo-CellDialogClass.java
, which defines a class called Ui_GoToCellDialogClass
that reproduces the dialog we designed using Qt Designer. We create an instance of this class and keep a reference to it in a private field called ui
.
In the constructor, we call the Ui_GoToCellDialogClass
’s setupUi()
method to create and lay out the widgets and to set their properties and signal–slot connections, including automatic connections for slots that follow the naming convention on_
objectName
_
signalName
()
.
A convenient feature of the Eclipse integration is that it is easy to make QWidget
subclasses available in the widget box to be dragged on to forms. We will briefly review the LabeledLineEdit
custom widget, and then describe how to make it available in Qt Designer’s widget box.
When we create custom widgets for use with Qt Designer, it is often convenient to provide properties that the programmer can change to customize the widget. The screenshot in Figure C.3 shows a custom LabeledLineEdit
widget in a form. The widget has two custom properties, labelText
and editText
, that can be set in the property editor. In C++/Qt, properties are defined by means of the Q_PROPERTY()
macro. In Qt Jambi, introspection is used to detect pairs of accessor methods that follow the Qt naming convention xxx
()
/set
Xxx
()
or the Java naming convention get
Xxx
()
/set
Xxx
()
. It is also possible to specify other properties and to hide automatically detected properties using annotations.
import com.trolltech.qt.*; import com.trolltech.qt.gui.*; public class LabeledLineEdit extends QWidget {
The first import
declaration is needed to access Qt Jambi’s @QtPropertyReader()
and @QtPropertyWriter()
annotations, which let us export properties to Qt Designer.
@QtPropertyReader(name="labelText") public String labelText() { return label.text(); } @QtPropertyWriter(name="labelText") public void setLabelText(String text) { label.setText(text); } @QtPropertyReader(name="editText") public String editText() { return lineEdit.text(); } @QtPropertyWriter(name="editText") public void setEditText(String text) { lineEdit.setText(text); }
For read-only properties, we can simply use the @QtPropertyReader()
annotation and provide a getter method. Here we want to provide read-write properties, so each has a getter and a setter. For this example, we could have omitted the annotations, since the accessor methods follow the Qt naming convention.
public LabeledLineEdit(QWidget parent){ super(parent); label = new QLabel(); lineEdit = new QLineEdit(); label.setBuddy(lineEdit); QHBoxLayout layout = new QHBoxLayout(); layout.addWidget(label); layout.addWidget(lineEdit); setLayout(layout); } private QLabel label; private QLineEdit lineEdit;
The constructor is quite conventional. To be eligible for use in the widget box, we must provide a constructor that takes a single QWidget
argument.
public static void main(String[] args) { QApplication.initialize(args); LabeledLineEdit testLabeledLineEdit = new LabeledLineEdit(null); testLabeledLineEdit.setLabelText("&Test"); testLabeledLineEdit.show(); QApplication.exec(); } }
Eclipse generates the main()
method automatically. We have passed null
as the argument to the LabeledLineEdit
constructor and added a line to set the label’s text property.
Once we have a custom widget, we can add it to a project by copying its .java
file into the project’s src
in the package explorer. Then we invoke the project’s Properties dialog and click the Qt Designer Plugins page. This page lists all the suitable QWidget
subclasses that are in the project. We just need to check the Enable plugin checkbox for any of the subclasses that we want to appear in the widget box and click OK. The next time we edit a form using the integrated Qt Designer, the widgets we have added to the project as plugins will appear at the bottom of the widget box in a separate section.
This concludes our brief introduction to using Eclipse for Qt Jambi programming. Eclipse provides a powerful and functional IDE with many conveniences for software development. And with the Qt Jambi integration in place, it is possible to create Qt Jambi applications, including those that use Qt Designer, completely within the Eclipse environment. Trolltech also provides a C++/Qt Eclipse integration with most of the same benefits as the Qt Jambi one.
Qt Jambi lets C++ programmers easily integrate their Qt code with Java. To make our own custom C++ components available to Qt Jambi, we can use the Qt Jambi Generator, which takes a set of C++ header files and an XML file that provides some information about the C++ classes that we want to wrap and produces Java bindings for our C++ components. The Qt Jambi API itself is created using the generator.
Figure C.4 illustrates the process. After running the generator, we obtain some Java files that we must compile using the Java compiler, and some .h
and .cpp
files that we must compile into a C++ shared library.
To illustrate the process, we will provide bindings for the data-only PlotSettings
class and for the Plotter
widget that we developed in Chapter 5 (p. 121). We will then use the bindings in a Java application. Figure C.5 shows the application running.
The header file we need must define (or include header files that define) all the classes necessary for the library we will build:
#include <QtGui> #include "../plotter/plotter.h"
We assume that the Plotter example code lies in a directory parallel to the Qt Jambi wrapper. We also need an XML file to tell the generator what to wrap and how to wrap it. The file is called jambiplotter.xml
:
<typesystem package="com.softwareinc.plotter" default-superclass="com.trolltech.qt.QtJambiObject"> <load-typesystem name=":/trolltech/generator/typesystem_core.txt" generate="no" /> <load-typesystem name=":/trolltech/generator/typesystem_gui.txt" generate="no" /> <object-type name="Plotter" /> <value-type name="PlotSettings" /> </typesystem>
In the outer tag, we specify a Java package name of com.softwareinc.plotter
for the Plotter component. The <load-typesystem>
tags import the information concerning the QtCore and QtGui modules.
The <object-type>
and <value-type>
tags specify the two C++ classes we want to make available. We have specified that the Plotter
class is a C++ “object type”; this is suitable for objects that cannot be copied, such as widgets. In contrast, the PlotSettings
class is treated as a C++ “value type”.
To Qt Jambi users, there is no obvious difference between the two. The distinction is important when the generator maps C++ APIs to Java APIs. For example, if a “value type” is returned from a method, the generator will ensure that a new independent object is returned (to avoid side effects), but if the returned type is an object type, a reference to the original object is returned.
We will need two environment variables, one specifying the path to Qt Jambi, the other to Java. Here is how we set them on Unix systems (using the Bash shell):
export JAMBIPATH=$HOME/qtjambi-linux32-gpl-4.3.2_01 export JAVA=/usr/java/jdk1.6.0_02
On Windows, we would write
set JAMBIPATH=C:QtJambi set JAVA="C:Program FilesJavajdk1.6.0_02"
Naturally, the version numbers and directories may be different for your system. From now on, we will assume that JAMBIPATH
and JAVA
are available. Once we have the header and XML files, we can run the generator in a console:
$JAMBIPATH/bin/generator jambiplotter.h jambiplotter.xml
If Qt Jambi has been installed locally rather than system-wide, this may fail on some systems. The solution is to provide a suitable path to Qt Jambi’s libraries:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$JAMBIPATH/lib
Again, we have used the Bash shell’s syntax. On Mac OS X, the relevant environment variable is called DYLD_LIBRARY_PATH
. On Windows, the equivalent is achieved by adding to the PATH
:
set PATH=%PATH%;%JAMBIPATH%lib
Now, on Windows, we can run the generator like this:
%JAMBIPATH%ingenerator jambiplotter.h jambiplotter.xml
The code generation takes a few moments, and outputs some summary information on the console. For our example, the generator produced the following files, in two parallel directories:
../com/softwareinc/plotter/PlotSettings.java ../com/softwareinc/plotter/Plotter.java ../com/softwareinc/plotter/QtJambi_LibraryInitializer.java ../cpp/com_softwareinc_plotter/com_softwareinc_plotter.pri ../cpp/com_softwareinc_plotter/metainfo.cpp ../cpp/com_softwareinc_plotter/metainfo.h ../cpp/com_softwareinc_plotter/qtjambi_libraryinitializer.cpp ../cpp/com_softwareinc_plotter/qtjambishell_PlotSettings.cpp ../cpp/com_softwareinc_plotter/qtjambishell_PlotSettings.h ../cpp/com_softwareinc_plotter/qtjambishell_Plotter.cpp ../cpp/com_softwareinc_plotter/qtjambishell_Plotter.h
We must now compile both the Java and the C++ files, but before we do this we should make sure that the CLASSPATH
environment variable is set correctly. For example, if we are using the Bash shell, we might do this:
export CLASSPATH=$CLASSPATH:$JAMBIPATH/qtjambi.jar:$PWD:$PWD/..
Here we have extended the existing CLASSPATH
with the Qt Jambi .jar
file, with the current directory, and with the current directory’s parent directory. We need the parent directory so that we can access the parallel com
directory. On Windows, the syntax would be
set CLASSPATH=%CLASSPATH%;%JAMBIPATH%qtjambi.jar;%CD%;%CD%..
We can now compile the .java
files into .class
files:
cd ../com/softwareinc/plotter javac *.java
After compiling the .java
files, we must return to the jambiplotter
directory. Here, the next step is to create the C++ shared library that provides the C++ code for Plotter
and PlotSettings
, as well as the C++ wrapper code produced by the generator. We begin by creating a .pro
file:
TEMPLATE = lib TARGET = com_softwareinc_plotter DLLDESTDIR = . HEADERS = ../plotter/plotter.h SOURCES = ../plotter/plotter.cpp RESOURCES = ../plotter/plotter.qrc INCLUDEPATH += ../plotter $$(JAMBIPATH)/include $$(JAVA)/include unix { INCLUDEPATH += $$(JAVA)/include/linux } win32 { INCLUDEPATH += $$(JAVA)/include/win32 } LIBS += -L$$(JAMBIPATH)/lib -lqtjambi include(../cpp/com_softwareinc_plotter/com_softwareinc_plotter.pri)
The TEMPLATE
variable must be set to lib
since we want to create a shared library rather than an application. The TARGET
variable specifies the name of the Java package but with underscores used instead of periods, and DLLDESTDIR
specifies where the shared library (or DLL) should be put. The INCLUDEPATH
variable must be extended to include the source directory (since it is not the current directory in this case), the Qt Jambi include path, the Java SDK’s include path, and the Java SDK’s platform-specific include path. (We cover the unix
and win32
syntaxes in Appendix B.) We must also include the Qt Jambi library itself, which we do in the LIBS
entry. The include()
directive at the end is used to access the C++ files the generator produced. Once we have the .pro
file, we can run qmake
and make
as usual to build the library.
Now that we have the shared library and suitable Java wrapper code, we are ready to make use of them in an application. The Jambi Plotter application creates a PlotSettings
and a Plotter
object and uses them to display some random data. The important point is that they are used just like any other Java or Qt Jambi class. The whole application is quite small, so we will show it in full:
import java.lang.Math; import java.util.ArrayList; import com.trolltech.qt.core.*; import com.trolltech.qt.gui.*; import com.softwareinc.plotter.Plotter; import com.softwareinc.plotter.PlotSettings; public class JambiPlotter { public static void main(String[] args) { QApplication.initialize(args); PlotSettings settings = new PlotSettings(); settings.setMinX(0.0); settings.setMaxX(100.0); settings.setMinY(0.0); settings.setMaxY(100.0); int numPoints = 100; ArrayList<QPointF> points0 = new ArrayList<QPointF>(); ArrayList<QPointF> points1 = new ArrayList<QPointF>(); for (int x = 0; x < numPoints; ++x) { points0.add(new QPointF(x, Math.random() * 100)); points1.add(new QPointF(x, Math.random() * 100)); } Plotter plotter = new Plotter(); plotter.setWindowTitle(plotter.tr("Jambi Plotter")); plotter.setPlotSettings(settings); plotter.setCurveData(0, points0); plotter.setCurveData(1, points1); plotter.show(); QApplication.exec(); } }
We import a couple of Java’s standard libraries and the Qt Jambi libraries that we need, as well as the PlotSettings
and Plotter
classes. We could just as easily have written import com.softwareinc.plotter.*
.
After initializing the QApplication
object, we create a PlotSettings
object and set some of its values. The C++ version of this class has minX
, maxX
, minY
, and maxY
as public variables. Unless told otherwise, the Qt Jambi generator produces accessor methods for such variables, using the Qt naming convention (e.g., minX()
and setMinX()
). Once we have suitable plot settings, we generate two lots of curve data, with 100 random points each. In C++/Qt, the points of each curve are held as a QVector<QPointF>
; in Qt Jambi, we pass an ArrayList<QPointF>
instead, relying on Qt Jambi to transform from one to the other as needed.
With the settings and curve data ready, we create a new Plotter
object with no parent (to make it a top-level window). Then we give the plotter the plot settings, and the data for two curves, and call show()
to make the plotter visible. Finally, we call QApplication.exec()
to start off the event loop.
When we compile the application, we must be careful to include not only the normal CLASSPATH
but also the path to the com.softwareinc.plotter
package. To run the application, we must also set up a couple of additional environment variables, to ensure that the loader will find Qt Jambi and our bindings. On Windows, we must set PATH
as follows:
set PATH=%PATH%;%JAMBIPATH%in;%CD%
On Unix, we must set LD_LIBRARY_PATH
:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$JAMBIPATH/lib:$PWD
On Mac OS X, the environment variable is called DYLD_LIBRARY_PATH
. Also, on all three platforms, we must set QT_PLUGIN_PATH
to include Qt Jambi’s plugins
directory. For example:
set QT_PLUGIN_PATH=%QT_PLUGIN_PATH%;%JAMBIPATH%plugins
To compile and run Jambi Plotter on all platforms, thanks to our additions to the CLASSPATH
, we can simply type this:
javac JambiPlotter.java java JambiPlotter
We have now completed the example, and shown how to make use of C++ components in Qt Jambi applications. In fact, the Qt Jambi generator that is the basis of making C++ components available to Java offers many more features than this brief introduction has shown. Although the generator supports only a subset of C++, this subset comprises all of the most common C++ constructs, including multiple inheritance and operator overloading. The generator is documented in full at http://doc.trolltech.com/qtjambi-4.3.2_01/com/trolltech/ qt/qtjambi-generator.html
. We will briefly mention just a few features we didn’t need in the example, to give a flavor of what’s available.
The key to influencing how the generator works is what we put in the XML file we give it. For example, if we have multiple inheritance in C++, one straightforward way to handle this in Qt Jambi is to identify just one of the classes concerned as an “object type” or “value type” in the type system, and identify all the others as “interface types”.
It is also possible to provide more natural method signatures. For example, instead of using an ArrayList<QPointF>
to pass the points for a curve, it would be nicer to pass a QPointF
array. This involves hiding the original C++ method and replacing it with a Java method that accepts a QPointF[]
and calls the original C++ method behind the scenes. We can achieve this by modifying the jambiplotter.xml
file. We originally declared the C++ Plotter
type with an entry like this:
<object-type name="Plotter" />
We will replace the preceding line with a more sophisticated version:
<object-type name="Plotter"> <modify-function signature="setCurveData(int,const QVector<QPointF>&)"> <access modifier="private" /> <rename to="setCurveData_private" /> </modify-function> <inject-code> public final void setCurveData(int id, com.trolltech.qt.core.QPointF points[]) { setCurveData_private(id, java.util.Arrays.asList(points)); } </inject-code> </object-type>
In the <modify-function>
element, we rename the C++ setCurveData()
method to be setCurveData_private()
and change its access specifier to private
, thereby preventing access to it from outside the class’s own methods. Notice that we must escape XML’s special characters ‘<’, ‘>’, and ‘&’ in the signature
attribute.
In the <inject-code>
element, we implement a custom setCurveData()
method in Java. This method accepts a QPointF[]
argument and simply calls the private setCurveData_private()
method, converting the array to the list that the C++ method expects.
Now we can create and populate QPointF
arrays in a more natural manner:
QPointF[] points0 = new QPointF[numPoints]; QPointF[] points1 = new QPointF[numPoints]; for (int x = 0; x < numPoints; ++x) { points0[x] = new QPointF(x, Math.random() * 100); points1[x] = new QPointF(x, Math.random() * 100); }
The rest of the code is the same as before.
In some cases, when classes are wrapped, the generator produces code that uses QNativePointer
. This type is a wrapper for C++ “value type” pointers and works for both pointers and arrays. The file mjb_nativepointer_api.log
specifies any generated code that uses QNativePointer
. The Qt Jambi documentation recommends replacing any code that uses QNativePointer
and provides step-by-step instructions for how to do this.
Sometimes we will need to include additional import
declarations in the generated .java
files. This is easily achieved using the <extra-includes>
tag, and is fully described in http://doc.trolltech.com/qtjambi-4.3.2_01/com/trolltech/qt/ qtjambi-typesystem.html
.
The Qt Jambi generator is a powerful and versatile tool for making C++/Qt classes seamlessly available to Java programmers, and makes it possible to combine the strengths of C++ and Java in a single project.