Hello World!

Now that Kotlin/Native is set up, let’s build our first gtk-kn app.

First, create a GTK Application instance with an application ID. To do this, add the gtk-kn dependency to your build.gradle.kts file. Open the file and replace // Specify dependencies here with:

implementation("org.gtkkn:gtk4:0.0.1-SNAPSHOT")

Next, update hello.kt with the following content:

// hello.kt
import org.gtkkn.bindings.gio.ApplicationFlags
import org.gtkkn.bindings.gtk.Application

private const val APP_ID = "org.gtkkn.samples.gtk.playground"

fun main() {
    Application(APP_ID, ApplicationFlags.FLAGS_NONE)
        .run(0, emptyList())
}

To build the project, run this command from the root directory:

./gradlew runDebugExecutableLinuxX64

The build completes, but you’ll see a warning in the terminal:

Warning

GLib-GIO-WARNING **: 20:36:01.273: Your application does not implement g_application_activate() and has no handlers connected to the ‘activate’ signal. It should do one of these.

GTK indicates that something should be executed in the activate step. Let’s add a GTK ApplicationWindow:

// hello.kt
import org.gtkkn.bindings.gio.ApplicationFlags
import org.gtkkn.bindings.gtk.Application
import org.gtkkn.bindings.gtk.ApplicationWindow

private const val APP_ID = "org.gtkkn.samples.gtk.playground"

fun main() {
    // Create a new application
    val app = Application(APP_ID, ApplicationFlags.FLAGS_NONE)

    // Connect to "activate" signal of `app`
    app.connectActivate {

        // Create a window and set the title
        val window = ApplicationWindow(app)
        window.setTitle("My GTK App")

        // Present window
        window.present()
    }

    // Run the application
    app.run(0, emptyList())
}

That’s better! Now we have a working window. Next, let’s add a button:

samples/gtk/hello-world/src/nativeMain/kotlin/hello.kt
private const val APP_ID = "org.gtkkn.samples.gtk.helloworld"

fun main() {
    // Create a new application
    val app = Application(APP_ID, ApplicationFlags.FLAGS_NONE)

    // Connect to "activate" signal of `app`
    app.connectActivate {
        // Create a button with label and margins
        val button = Button()
        button.setLabel("Click me!")
        button.setMargins(12)

        // Connect to "clicked" signal of `button`
        button.connectClicked {
            // Set the label to "Hello World!" after the button has been clicked on
            button.setLabel("Hello World!")
        }

        // Create a window and set the title
        val window = ApplicationWindow(app)
        window.title = "My GTK App"
        window.child = button

        // Present window
        window.present()
    }

    // Run the application
    app.runApplication()
}

Now, you’ll see a button labeled "Press me!" in the window. When clicked, it changes to "Hello World!".

Congratulations! You’ve just created your first gtk-kn app.