How to make the text scrollable with canvas.NewText() with fyne Go

Issue

I am new to programming and i want to develop a application but i need show to users very large text in my application.
I am not sure widget.NewRichTextWithText() is for this purpose.
This code working as i expected.

package main

import (
    "strings"

    "fyne.io/fyne/v2"
    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/container"
    "fyne.io/fyne/v2/widget"
)

func main() {
    a := app.New()
    
    w := a.NewWindow("Some Practice")
    
    w.Resize(fyne.NewSize(400, 400))
    
    text := widget.NewRichTextWithText((strings.Repeat("this\n", 100)))
    
    c := container.NewMax(container.NewVScroll(text))
    
    w.SetContent(c)
    
    w.ShowAndRun()
}

But this one does not work.

package main

import (
    "image/color"
    "strings"

    "fyne.io/fyne/v2"
    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/canvas"
    "fyne.io/fyne/v2/container"
)

func main() {
    a := app.New()
    
    w := a.NewWindow("Some Practice")
    
    w.Resize(fyne.NewSize(400, 400))
    
    text := canvas.NewText(strings.Repeat("this\n", 100), color.White)
    
    c := container.NewMax(container.NewVScroll(text))
    
    w.SetContent(c)
    
    w.ShowAndRun()
}

Becuase the " \n " showing as invalid character instead of new line when i run the application.
My aim is showing very large text "top to bottom scrollable" with canvas.NewText() but " \n " character does not work. Instead of top to bottom scrollable showing text it is printing this as this?this?this?

Solution

Use widget.Label to display "simple" texts:

text := widget.NewLabel(strings.Repeat("this\n", 100))

Note that widget.Label can be "styled" (e.g. you can make it italic or bold).

widget.RichText should be used if you want to display text that has parts (called segments) with different styles and formatting. widget.Label can only be styled as a whole.

Answered By – icza

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.