rivo / tview

Terminal UI library with rich, interactive widgets — written in Golang
MIT License
11.09k stars 577 forks source link

Beginner Question Regarding Checkbox #885

Open daryl-williams opened 1 year ago

daryl-williams commented 1 year ago

I'm not sure if this is the right place to ask a newbie question, if there is a better place please let me know. I have a form with a number of checkboxes and I want to be able to set them all to checked when a button is clicked. I have some code as follows:

button := testForm.AddButton("Select all", func() {
    for i:=0; i<testForm.GetFormItemCount(); i++ {
      item := testForm.GetFormItem(i)
      //item.checked = true
      fmt.Printf("1. Item Type    = %T\n", item)
      fmt.Printf("2. Item Type    = %T\n", &item)
    }
}

I would like to be able to programmatically check each checkbox item. I have tried using item.SetChecked() but I am told:

item.SetChecked undefined (type tview.FormItem has no field or method SetChecked)

When I print out the item type of item I get tview.CheckBox and when I print the type of &item I get tview.FormItem and when I print the value (using %v) I get what appears to be a struct with 12 fields which is where I think the value I want to set resides.

Any help clearing this up would be appreciated, I have searched online and perused the demo code trying to find examples of how to work with checkboxes without much luck.

Regards,

Daryl

digitallyserviced commented 1 year ago

@daryl-williams

Thi is something that is a basic Go concept. You have to cast it to the interface/type that you want to invoke a method for.

FormItem is an interface type that the Checkboxes, TextView, Radio, Buttons, etc... all implement, so you just have to coerce back to the original Primitive/Widget *tview.Checkbox. Here is a demo that does it.

https://github.com/rivo/tview/blob/ba6a2a345459809bc1cc8b7d8647b5f64c2bed70/demos/unicode/main.go#L20

This should do it

button := testForm.AddButton("Select all", func() {
    for i:=0; i<testForm.GetFormItemCount(); i++ {
      // your good old standard Go cast of a type, with a guard in there to make sure this item
      // will work
      if item, ok := testForm.GetFormItem(i).(*tview.Checkbox); ok {
        item.SetChecked(true)
      }

      fmt.Printf("1. Item Type    = %T\n", item)
      fmt.Printf("2. Item Type    = %T\n", &item)
    }
}
daryl-williams commented 1 year ago

@digitallyserviced

Thanks for your reply, I appreciate the explanation and the example code, it really helped me to understand the Go language better and helped me get that code working.

Regards

Daryl