Work in progress

The content of this page was not yet updated for Godot 4.2 and may be outdated. If you know how to improve this page or you can confirm that it's up to date, feel free to open a pull request.

自訂 GUI 控制項

控制項真多呀……

不過這是永遠不嫌多的。每個 GUI 程式師幾乎都癡迷於建立自己的自訂控制項,讓這些控制項讓自己的要求工作。Godot 提供了大量的控制項,但它們可能並不完全如您所願的方式工作。在使用支援對角捲軸的拉取請求與開發人員聯繫之前,至少應該瞭解如何從腳本輕鬆地建立這些控制項。

繪製

談到繪製, 推薦看看這篇 2D 中的自訂繪圖 的教學. 同樣的原理適用與控制項繪製. 這裡有些函式值得一提, 因為它們在繪製時有用, 所以接下來將進行詳細說明:

檢查控制項的大小

與2D節點不同,"size" 對控制項很重要, 因為它有助於在適當的佈局中組織它們. 為此, 我們提供了 Control.rect_size 屬性. 在 _draw() 中檢查它以確保所有東西都在範圍之內.

檢查輸入焦點

一些控制項(如按鈕或文字編輯器)可為鍵盤或手柄輸入提供輸入焦點. 這方面的例子是輸入文字或按下一個按鈕. 這可以通過 Control.focus_mode 屬性來控制. 繪製時, 如果控制項支援輸入焦點, 總是希望顯示某種指示來表明(高亮, 方框等), 目前這是焦點控制項. 為了檢查這個狀態, 存在一個 Control.has_focus() 的方法. 例子

func _draw():
    if has_focus():
         draw_selected()
    else:
         draw_normal()

調整大小

如前所述, 尺寸對控制項是很重要的. 這可以讓它們在設定網格, 容器或錨定時以正確佈局. 控制項, 在大多數情況下, 提供了一個 minimum size , 以幫助它們正確佈局. 例如, 如果控制項被垂直放置在彼此的頂部, 使用 VBoxContainer , 最小尺寸將確保你的自訂控制項不會被容器中的其他控制項擠壓.

To provide this callback, just override Control._get_minimum_size(), for example:

func _get_minimum_size():
    return Vector2(30, 30)

或者, 使用函式進行設定:

func _ready():
    set_custom_minimum_size(Vector2(30, 30))

輸入

控制項為輸入事件的管理提供了一些輔助工具,比普通節點要方便一點。

輸入事件

在此之前有幾個關於輸入的教學, 但值得一提的是, 控制項有一個特殊的輸入方法, 只有在以下情況下才起作用:

  • 滑鼠指標懸停在控制項上.

  • 滑鼠按鍵在此控制項上被按下 (控制項始終捕獲輸入, 直到按鈕被釋放)

  • 控制項通過以下方式提供鍵盤和手柄焦點 Control.focus_mode.

This function is Control._gui_input(). Simply override it in your control. No processing needs to be set.

extends Control

func _gui_input(event):
   if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
       print("Left mouse button was pressed!")

有關事件本身的詳細資訊,請查看 使用 InputEvent 教學。

通知

控制項也有許多有用的通知, 這些通知不存在專門的回呼函式, 但可以用_notification回呼函式來檢查:

func _notification(what):
    match what:
        NOTIFICATION_MOUSE_ENTER:
            pass # Mouse entered the area of this control.
        NOTIFICATION_MOUSE_EXIT:
            pass # Mouse exited the area of this control.
        NOTIFICATION_FOCUS_ENTER:
            pass # Control gained focus.
        NOTIFICATION_FOCUS_EXIT:
            pass # Control lost focus.
        NOTIFICATION_THEME_CHANGED:
            pass # Theme used to draw the control changed;
            # update and redraw is recommended if using a theme.
        NOTIFICATION_VISIBILITY_CHANGED:
            pass # Control became visible/invisible;
            # check new status with is_visible().
        NOTIFICATION_RESIZED:
            pass # Control changed size; check new size
            # with get_size().
        NOTIFICATION_MODAL_CLOSE:
            pass # For modal pop-ups, notification
            # that the pop-up was closed.