Открыть боковую панель
Aurora OS
Kotlin Multiplatform
QtBindings
Коммиты
3fc24123
Коммит
3fc24123
создал
Май 07, 2025
по автору
Ilya Pankratov
Просмотр файлов
feat: create README
владелец
2c501545
Изменения
2
Скрыть пробелы
Построчно
Рядом
README.md
Просмотр файла @
3fc24123
[
**EN**
](
README.md
)
|
[
RU
](
README.ru.md
)
# QtBindings
A gradle plugin that generates Qt bindings for Kotlin code compiled into a
C static or shared library. It helps to share business logic using Kotlin
Multiplatform and create UI using Qt Quick (QML).
**Supported KMP targets**
: linuxArm64, linuxX64.
## Add QtBindings to the project
Add plugin to the build script and set up linux target(s) to compile
static or shared library:
```
kotlin
plugins
{
id
(
"org.jetbrains.kotlin.multiplatform"
)
version
"2.1.10"
id
(
"com.google.devtools.ksp"
)
version
"2.1.10-1.0.29"
id
(
"ru.auroraos.kmp.qtbindings"
)
version
"0.1.0"
}
kotlin
{
val
linuxTargets
=
listOf
(
linuxX64
(),
linuxArm64
())
linuxTargets
.
forEach
{
it
->
it
.
binaries
{
staticLib
(
"shared"
)
}
}
}
qtBindings
{
libName
=
"shared"
}
```
**Note**
: The
`libName`
**must match**
the name of the compiled static or
dynamic library for the linux target.
## Usage
Annotation
`QtExport`
can be applied to the top-level classes or function
to create Qt bindings for them.
*
Export top-level Kotlin function
```
kotlin
import
ru.auroraos.kmp.qtbindings.QtExport
@QtExport
fun
helloWorld
()
=
println
(
"Hello, World!"
)
```
<details><summary>
Generated Qt function
</summary>
<p>
The QtBindings plugin will generate this Qt function:
```
cpp
void
helloWorld
();
```
</p>
</details>
*
Export top-level Kotlin class
```
kotlin
import
ru.auroraos.kmp.qtbindings.QtExport
@QtExport
class
Calculator
()
{
fun
sum
(
x
:
Int
,
y
:
Int
)
:
Int
=
x
+
y
fun
multiply
(
x
:
Int
,
y
:
Int
)
:
Int
=
x
*
y
}
```
<details><summary>
Generated Qt class
</summary>
<p>
The QtBindings plugin will generate this Qt class:
```
cpp
class
Calculator
{
public:
Calculator
();
Calculator
(
Calculator
&&
other
);
Calculator
(
libshared_kref_ru_auroraos_example_Calculator
ptr
);
~
Calculator
();
Calculator
&
operator
=
(
Calculator
&&
other
);
int
sum
(
int
x
,
int
y
)
const
;
int
multiply
(
int
x
,
int
y
)
const
;
libshared_kref_ru_auroraos_example_Calculator
unsafeKotlinPointer
()
const
;
private:
libshared_kref_ru_auroraos_example_Calculator
d_ptr
;
};
```
</p>
</details>
*
Export suspend function
```
kotlin
import
kotlinx.coroutines.delay
import
ru.auroraos.kmp.qtbindings.QtExport
@QtExport
suspend
fun
calculateAsync
(
x
:
Int
,
y
:
Int
)
:
Int
{
delay
(
1000
)
return
x
+
y
}
```
<details><summary>
Generated Qt function that returns QFuture
</summary>
<p>
The QtBindings plugin will generate this Qt function:
```
cpp
QFuture
<
int
>
calculateAsync
(
int
x
,
int
y
);
```
</p>
</details>
**Note**
: Generated Qt bindings (
`cpp`
and
`hpp`
files) are located in
`build/generated/ksp/[linuxTargetName]/[linuxMainSourceSetName]/resources`
**Do not forget**
to add the compiled C library for the Linux target to the Qt project
to make the Qt bindings work.
Ways to use Qt bindings in a Qt project:
*
Compile static or shared library from the generated Qt bindings and add it to the project
*
Add the generated Qt binding source code to the project's build system (qmake, cmake, meson)
## Mappings
| Kotlin | Qt (C++) |
|------------------------------------------------|--------------------------------------------------------------------------|
| Primitives:
`Unit`
,
`Bool`
,
`Int`
,
`Long`
, etc |
`void`
,
`bool`
,
`int`
,
`long long`
, etc |
|
`String`
|
`QString`
|
|
`List`
,
`MutableList`
|
`QList`
|
|
`suspend`
functions (coroutines) | Functions that returns
`QFuture`
|
| Public top-level Kotlin function | Public top-level Qt (C++) function |
| Public top-level Kotlin class | Public top-level Qt (C++) class |
|
`data`
class | Qt (C++) class with copy constructor, copy operator, getters and setters |
## Known limitations
*
Qt collections (
`QList`
) are copies of Kotlin ones. You need create a setter
or special kotlin function that updates Kotlin list.
```
kotlin
import
ru.auroraos.kmp.qtbindings.QtExport
@QtExport
data class
Example
(
val
example
:
MutableList
<
String
>)
```
For example, generated code for the Kotlin
`Example`
class:
```
cpp
class
Example
{
public:
Example
(
const
QList
<
QString
>
&
example
);
Example
(
const
Example
&
other
);
Example
(
Example
&&
other
);
Example
(
libshared_kref_ru_auroraos_example_Example
ptr
);
~
Example
();
Example
&
operator
=
(
const
Example
&
other
);
Example
&
operator
=
(
Example
&&
other
);
QList
<
QString
>
getExample
()
const
;
// Returns copy of the Kotlin list
void
setExample
(
const
QList
<
QString
>
&
set
);
// Change Kotlin list
libshared_kref_ru_auroraos_example_Example
unsafeKotlinPointer
()
const
;
private:
libshared_kref_ru_auroraos_example_Example
d_ptr
;
};
```
`getExample`
function will return
**COPY**
of Kotlin
`MutableList`
.
You need to use
`setExample`
function to change its value in the
`Example`
class in the Kotlin side. After you have changed the value
of the list using
`setExample`
, you will get the updated value in the
`getExample`
function.
*
Nested classes are not supported yet
*
Objects are not supported yet
*
Enums are not supported yet
## How to build and publish locally
Prerequisites:
*
JDK 11
```
kotlin
./
gradlew
publishToMavenLocal
```
README.ru.md
0 → 100644
Просмотр файла @
3fc24123
[
**EN**
](
README.md
)
|
[
RU
](
README.ru.md
)
# QtBindings
QtBindings - это Gradle-плагин, генерирующий Qt-обёртки для Kotlin-кода,
скомпилированного в статическую или динамическую С-библиотеку. Он помогает
разделять бизнес-логику для Qt-платформ и создавать UI с помощью Qt Quick (QML).
**Поддерживаемые KMP цели:**
linuxArm64, linuxX64.
## Добавление QtBindings в проект
Для работы нужно добавить Gradle-плагин QtBindings в сборочный скрипт (build.gradle.kts)
проекта. При этом для корректной работы также должны быть подключены плагины
Kotlin Multiplatform и KSP. После подключения всех необходимых плагинов нужно
настроить компиляцию статической или динамической С-библиотеки для Linux целей:
```
kotlin
plugins
{
id
(
"org.jetbrains.kotlin.multiplatform"
)
version
"2.1.10"
id
(
"com.google.devtools.ksp"
)
version
"2.1.10-1.0.29"
id
(
"ru.auroraos.kmp.qtbindings"
)
version
"0.1.0"
}
kotlin
{
val
linuxTargets
=
listOf
(
linuxX64
(),
linuxArm64
())
linuxTargets
.
forEach
{
it
->
it
.
binaries
{
staticLib
(
"shared"
)
}
}
}
qtBindings
{
libName
=
"shared"
}
```
**Замечание**
: Свойство
`libName`
**должно соответствовать**
названию скомпилированной
библиотеки.
## Использование
Аннотация
`QtExport`
может быть применена к верхнеуровневым классам и функциям, чтобы
сгенерировать Qt-обёртки для них.
*
Генерация Qt-обёртки для верхнеуровневой Kotlin-функции
```
kotlin
import
ru.auroraos.kmp.qtbindings.QtExport
@QtExport
fun
helloWorld
()
=
println
(
"Hello, World!"
)
```
<details><summary>
Сгенерированная Qt-функция
</summary>
<p>
```
cpp
void
helloWorld
();
```
</p>
</details>
*
Генерация Qt-обёртки для верхнеуровневого Kotlin-класса
```
kotlin
import
ru.auroraos.kmp.qtbindings.QtExport
@QtExport
class
Calculator
()
{
fun
sum
(
x
:
Int
,
y
:
Int
)
:
Int
=
x
+
y
fun
multiply
(
x
:
Int
,
y
:
Int
)
:
Int
=
x
*
y
}
```
<details><summary>
Сгенерированный Qt-класс
</summary>
<p>
```
cpp
class
Calculator
{
public:
Calculator
();
Calculator
(
Calculator
&&
other
);
Calculator
(
libshared_kref_ru_auroraos_example_Calculator
ptr
);
~
Calculator
();
Calculator
&
operator
=
(
Calculator
&&
other
);
int
sum
(
int
x
,
int
y
)
const
;
int
multiply
(
int
x
,
int
y
)
const
;
libshared_kref_ru_auroraos_example_Calculator
unsafeKotlinPointer
()
const
;
private:
libshared_kref_ru_auroraos_example_Calculator
d_ptr
;
};
```
</p>
</details>
*
Генерация Qt-обёртки для suspend-функции (корутины)
```
kotlin
import
kotlinx.coroutines.delay
import
ru.auroraos.kmp.qtbindings.QtExport
@QtExport
suspend
fun
calculateAsync
(
x
:
Int
,
y
:
Int
)
:
Int
{
delay
(
1000
)
return
x
+
y
}
```
<details><summary>
Сгенерированная Qt-функция, возвращающая QFuture
</summary>
<p>
```
cpp
QFuture
<
int
>
calculateAsync
(
int
x
,
int
y
);
```
</p>
</details>
**Замечание**
: Сгенерированные Qt-обёртки (
`cpp`
и
`hpp`
файлы) расположены в
`build/generated/ksp/[linuxTargetName]/[linuxMainSourceSetName]/resources`
**Не забудьте**
добавить скомпилированную C-библиотеку в Qt-проект, чтобы
Qt-обёртки работали.
Способы использования Qt-обёрток в проекте:
*
Компиляция статической или динамической библиотеки из Qt-обёрток и подключение
этой библиотеки в Qt-проект
*
Добавление всех Qt-обёрток (
`cpp`
и
`hpp`
файлов) напрямую в систему
сборки (qmake, cmake, meson)
## Соответствия типов и конструкций
| Kotlin | Qt (C++) |
|--------------------------------------------------|--------------------------------------------------------------------------------------------|
| Примитивы:
`Unit`
,
`Bool`
,
`Int`
,
`Long`
и т. д. |
`void`
,
`bool`
,
`int`
,
`long long`
и т. д. |
|
`String`
|
`QString`
|
|
`List`
,
`MutableList`
|
`QList`
|
|
`suspend`
-функции (корутины) | Функции, возвращающие
`QFuture`
|
| Публичные верхнеуровневые функции | Публичные верхнеуровневые функции |
| Публичные верхнеуровневые классы | Публичные верхнеуровневые классы |
|
`data`
-классы | Qt (C++) классы с конструктором копирования, оператором копирования, геттерами и сеттерами |
## Известные ограничения
*
Qt-коллекции (
`QList`
) являются копиями Kotlin-коллекций. Нужно создать сеттер для
изменения значений коллекции в Kotlin.
```
kotlin
import
ru.auroraos.kmp.qtbindings.QtExport
@QtExport
data class
Example
(
val
example
:
MutableList
<
String
>)
```
Например, сгенерированный код для класса
`Example`
:
```
cpp
class
Example
{
public:
Example
(
const
QList
<
QString
>
&
example
);
Example
(
const
Example
&
other
);
Example
(
Example
&&
other
);
Example
(
libshared_kref_ru_auroraos_example_Example
ptr
);
~
Example
();
Example
&
operator
=
(
const
Example
&
other
);
Example
&
operator
=
(
Example
&&
other
);
QList
<
QString
>
getExample
()
const
;
// Returns copy of the Kotlin list
void
setExample
(
const
QList
<
QString
>
&
set
);
// Change Kotlin list
libshared_kref_ru_auroraos_example_Example
unsafeKotlinPointer
()
const
;
private:
libshared_kref_ru_auroraos_example_Example
d_ptr
;
};
```
Функция
`getExample`
вернёт
**копию**
Kotlin-коллекции
`MutableList`
.
Необходимо использовать функцию
`setExample`
, чтобы изменить элементы в коллекции
класса
`Example`
. После того как значение коллекции будут изменено с помощью
`setExample`
, обновлённые значения могут быть получены с помощью функции
`getExample`
.
*
Вложенные классы не поддержаны
*
Kotlin-объекты не поддержаны
*
Перечисления (Enums) не поддержаны
## Как собрать QtBindings и опубликовать локально
Требования:
*
JDK 11
```
kotlin
./
gradlew
publishToMavenLocal
```
Редактирование
Предварительный просмотр
Поддерживает Markdown
0%
Попробовать снова
или
прикрепить новый файл
.
Отмена
You are about to add
0
people
to the discussion. Proceed with caution.
Сначала завершите редактирование этого сообщения!
Отмена
Пожалуйста,
зарегистрируйтесь
или
войдите
чтобы прокомментировать