Qt java bindings of the

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

QtJambi is a wrapper for using Qt in Java.

License

Unknown and 4 other licenses found

Licenses found

OmixVisualization/qtjambi

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

issue #158 issue #153 issue #152 issue #151 issue #150 issue #149 issue #148 issue #147

Git stats

Files

Failed to load latest commit information.

README.md

QtJambi - Java Bindings for Qt

QtJambi — Java Bindings for Qt

QtJambi is Qt bindings for the Java programming language originally developed by Trolltech, the predecessor of The Qt Company. The successive open source project provides bindings of Qt5 and Qt6 releases for latest Java JDK versions.

The bindings are generated by inspection of the C++ header files of the Qt implementation then emitting code to provide the necessary JNI (Java Native Interface) and .java files to provide linkage to Java. An application programmer using QtJambi would simply add the coresponding Java libraries (.jar files) to their Java project to be able to develop and deploy their application.

QtJambi is available for Java 8 or 11 and higher using Qt5.15 and Qt6 in Java on Windows, Android Linux and macOS. Most Qt modules are available as QtJambi module as listed here. All modules are published as Maven Artifact.

QtJambi is an open source project making the power of Qt available for your Java projects free of charge. However, this project is causing ongoing costs. Please consider supporting this project by donation. Your support is highly appreciated.

How To Build From Sources

If you just want to use QtJambi for your application development you can skip these instructions and simply use the provided binaries from the list of modules. Make yourself familiar with developing applications with QtJambi.

  • Apache Ant (min. 1.10.x)
  • Java Development Kit (e.g. OpenJDK, tested with Java 1.8 and 20)
  • Qt 5.15 or 6.x (using the Qt Online Installer)
  • Minimum required Qt modules: QtCore, QtQml, QtNetwork, QtConcurrent and QtXml
  • C++ compiler and make (Gcc, Clang, MSVC2019)
  • XCode command line tools (macOS only)

If you do’nt need the entire set of Qt modules available in Java edit property qtjambi.skipped.modules in build.properties and exclude Qt modules you don’t need. This saves compilation time. Although QtJambi build process requires the availability of QtQml, QtNetwork, QtConcurrent and QtXml, you can skip them from being generated as QtJambi module.

Pre-Build Steps On Windows

to be found in: —> Start Menu —> Programs —> Visual Studio 2022 —> Visual Studio Tools —> VC

> set JAVA_HOME_TARGET=path to your java jdk

> set PATH=. \apache-ant-1.10.3\bin;%PATH%

Pre-Build Steps On Linux and macOS

> export JAVA_HOME_TARGET=path to your java jdk

> export QTDIR=/opt/Qt/6.5.1/gcc_64 on Linux

> export QTDIR=/opt/Qt/6.5.1/macos on macOS

(This step may take several hours.)

> ant tests.generate tests.run

  • Find unit test results in directory TestResults .
  • Finally, find all Java libraries in directory $VERSION/deployment and all native libraries in platform- and configuration-specific subdirectory, e.g. native/windows-x64/release .

After building QtJambi for the running operation system you can additionally cross-compile QtJambi for other platforms. For instance if you want to build for Android use the following command (on Windows):

> ant -Dqmake=C:\Qt\6.5.1\android_x86_64\bin\qmake.bat library.native

or if you want to build for Linux arm:

> ant -Dqmake=/opt/Qt/6.5.1/arm-gnueabi/bin/qmake library.native

Just specify the third-platform cross-compiled qmake with -Dqmake=path .

Add qtjambi-VERSION.jar to the classpath of your Java project containing the most essential Qt Core, Gui and Widgets modules. If you use Maven to build your application simply add following dependency to your project:

dependency> groupId>io.qtjambigroupId> artifactId>qtjambiartifactId> version>$VERSIONversion> dependency>

(exchange $VERSION either by 5.15.15 or by 6.5.1 ).

Otherwise, download QtJambi JAR file from Maven Central Repository.

Create a file Test.java containing the following code:

import io.qt.widgets.*; public class Test < public static void main(String[] args) < QApplication.initialize(args); QMessageBox.information(null, "QtJambi", "Hello World!"); QApplication.shutdown(); > >
javac -cp qtjambi-6.5.1.jar Test.java

For execution you need the platform dependent binaries of QtJambi either as self-extracting bundle or as library file (e.b. dll). For instance, if you are working on Windows download qtjambi-native-windows-x64-VERSION.jar from Maven Central Repository and add it to java class path. Additionally, you need Qt. Use the Qt installer to install Qt on your system. Make sure you are using the same Qt version and QtJambi version (e.g. 5.15 or 6.x).

When running a QtJambi application you have to make the locations of Qt libraries known to Java. Therefore, use the PATH environment (LD_LIBRARY_PATH on Linux, DYLD_LIBRARY_PATH on macOS) or the Java runtime property java.library.path. By default, on Windows Qt libraries are located in bin directory and on Linux and macOS in lib directory. In case your Linux distribution provides Qt (of correct version) as system library you don’t need to specify library path.

The example program can be executed this way on Windows:

java -cp qtjambi-6.5.1.jar;. -Djava.library.path=C:\Qt\6.5.1\msvc2019_64\bin Test

On Linux it looks this way:

java -cp qtjambi-6.5.1.jar:. -Djava.library.path=path to>/Qt/6.5.1/gcc_64/lib Test

On macOS you additionally need to use the start parameter -XstartOnFirstThread:

java -cp qtjambi-6.5.1.jar:. -Djava.library.path=path to>/Qt/6.5.1/macos/lib -XstartOnFirstThread Test

In general, you can start learning how to use Qt in Java as it is introduced for C++. There are a couple of specifics for QtJambi that are introduced here. Instead of starting your program with a java command as shown above you can deploy your application as executable as described here.

 GNU LESSER GENERAL PUBLIC LICENSE QtJambi is Copyright (C) 1992-2009 Nokia. All rights reserved. Copyright (C) 2009-2023 Dr. Peter Droste, Omix Visualization GmbH & Co. KG. All rights reserved. You may use, distribute and copy QtJambi under the terms of [GNU Lesser General Public License version 2.1](LICENSE.LGPLv21). 
 GNU GENERAL PUBLIC LICENSE QtJambi is Copyright (C) 1992-2009 Nokia. All rights reserved. Copyright (C) 2009-2023 Dr. Peter Droste, Omix Visualization GmbH & Co. KG. All rights reserved. You may use, distribute and copy QtJambi under the terms of GNU Lesser General Public License version 3. That license references the [General Public License version 3](LICENSE.GPLv3). Other portions of the QtJambi may be licensed directly under this license. 

Источник

Заметка о Jambi (Qt Java bindings)

import com.trolltech.qt.gui.QApplication;
import com.trolltech.qt.gui.QGridLayout;
import com.trolltech.qt.gui.QLayout;
import com.trolltech.qt.gui.QPushButton;
import com.trolltech.qt.gui.QTextEdit;
import com.trolltech.qt.gui.QWidget;

public class Main
<
/*
* Класс нашего окна
*/
public static class MainWindow
extends QWidget

public MainWindow( )
<
setWindowTitle( «This is simple demo of JAmbi» );
initControls();
>

// Текстовое поле, от куда будем брать текст для вывода в консоль
private static final QTextEdit edit = new QTextEdit( «initial string» );

private void initControls()
<
// Создаём контейнер для виджетов
QLayout layout = new QGridLayout( this );

// Просто кнопка.
QPushButton button = new QPushButton( «push me» );

// Тут мы говорим Qt, что для «clicked» сигнала нужно
// вызвать «on_button1_clicked()» у объекта «this».
// Вместо this может быть любой другой объект
button.clicked.connect( this , «on_button1_clicked()» );

// добавляем виджеты в контейнер
layout.addWidget( edit );
layout.addWidget( button );
>

/* Создание диалога из сгенерённого класса-билдера */

// 1. Создаем «пустой» виджет
QWidget dialog = new QWidget();

// 2. Создаём инстанс билдера
Ui_Dialog1 dialogProto = new Ui_Dialog1();

// 3. Инициализируем визуальную часть
dialogProto.setupUi( dialog );

// 4. Делаем всё остальное (линкуем слоты и сигналы)
dialogProto.pushButton.clicked.connect( this , «on_pushButton_clicked()» );

void on_pushButton_clicked()
<
System.out.println( «Push button clicked» );
>
>

public static void main( String[] args )
<
// Создаём Qt приложение, что бы инициализировать библиотеку
// и графическую подсистему.
QApplication app = new QApplication( args );

QWidget mainWidget = new MainWindow();

Что бы инициализировать Qt создаём QApplication. Но самое интерсное как раз в MainWindow.
Первое, что мне очень понравилось, это простота назначения экшенов на сигналы. Джавовский reflection api и идея slot/signal образуют весьма удобный и просто в использовании механизм связывания.

Вторым на очереди был созданный в designer пользовательский интерфейс. Тут я встретил небольшой баг:
при попытке выполнить jambi_home/bin/juic -d ../project ../project/test.ui , я получил:
juic: not jambi file
Проблема оказалась в том, что juic ищет проперти language=«jambi» в ui ноде, но так как designer его там не прописал, проверка на валидность не проходит.

В финале я получил сгенеренный Ui_Dialog1.java, который содержал не готовый код виджета, а лишь билдер. Чтобы его использовать, достаточно создать пустой виджет и натравить на него инстанс метод setupUi(widget) класса билдера.
Все это происходит во время выполнения программы, что возможно не совсем хорошо, при создании окон с большим количеством элементов.
Все элементы интерфейса доступны как public members класса билдера, что делает решение не совсем обдуманным, потому что получается, что на каждый инстанс виджета будет инстан класса билдера.

Заключение

Jambi неплохая альтернатива swing/awt (в плане производительности, думаю, будет прирост). Лично мне она приглянулась простотой создания java gui. Но прежде чем использовать её в комерческом проекте, я бы подумал:
1. стоит ли прирост производительности стоимости лицензии
2. о возможных проблемах при распространении конечного продукта, потому что для каждой платформы нативная часть библиотеки своя.

Статья же — повод обсудить Jambi на Хабре. Очень хочется услышать коментарии людей, которые давно работают с данной библиотекой и применяют её в крупных проектах.

Источник

Читайте также:  And operation in python example
Оцените статью