Skip to content

Instantly share code, notes, and snippets.

@lordofscripts
Created December 14, 2023 17:54

Revisions

  1. lordofscripts created this gist Dec 14, 2023.
    36 changes: 36 additions & 0 deletions buttonPatternOnOff.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    // Go's Fyne GUI framework has some not-so-fine ways of making simple things more difficult than they should.
    // The problem lies in the OnTapped events that are declared for widgets such as Buttons. These, unlike .NET
    // have no way of determining the source/owner of the event because these functions have no parameters to
    // acomplish that.
    // As a use case, imagine a Go Fyne form with Enable & Disable buttons that operate on other widgets. How
    // would you go about disabling the button once it has been tapped (proper GUI behavior)?

    // 1. Declare the Button instances. Chicken & Egg problem, at this point we don't have an object instance to
    // use in the OnTapped callback to reconfigure the buttons.
    btnDisable := widget.NewButton("Disable", nil)
    btnEnable := widget.NewButton("Enable", nil)
    btnEnable.Disable() // by default the form is enabled

    // 2. Declare OnTapped callback for disabling/enabling the slave widgets and reconfigure both buttons
    var disableCB = func() {
    intSpinner.Disable()
    fintSpinner.Disable()
    dintSpinner.Disable()
    fdintSpinner.Disable()

    btnDisable.Disable() // no point in leaving it enabled when it is now a NOOP
    btnEnable.Enable() // but user should now be able to Enable
    }
    var enableCB = func() {
    intSpinner.Enable()
    fintSpinner.Enable()
    dintSpinner.Enable()
    fdintSpinner.Enable()

    btnEnable.Disable()
    btnDisable.Enable()
    }

    // 3. Now attach the callbacks
    btnDisable.OnTapped = disableCB
    btnEnable.OnTapped = enableCB