Search code examples
gofyne

Scrolling log text in a Fyne TextGrid automatically


I'm trying to use a widget to display text which will scroll vertically as more text is added.

I'm unable to figure out how to get the text to scroll, though. The closest I've come is enabling scrolling, but you have to manually scroll down as text is appended. I haven't found a way to "lock" resizing; if don't put the TextGrid into a scroll container, the application seems to jump in size outside the boundary of the monitor.

Is there a way to get the TextGrid to scroll automatically?

    appClient := app.New()
    winWindow := appClient.NewWindow("Test")

    txtEntry := widget.NewEntry()
    txtStatus := widget.NewLabel("Status")
    txtResults := widget.NewTextGrid()
    txtResults.ShowLineNumbers = true

    btnQuit := widget.NewButton("Quit", func() {
        appClient.Quit()
    })
    btnQuit.Resize(fyne.NewSize(300, 300))

    cntScrolling := container.NewScroll(txtResults)
    cntButtons := container.NewGridWithColumns(4, layout.NewSpacer(), layout.NewSpacer(), layout.NewSpacer(), btnQuit)
    cntContent := container.NewGridWithRows(4, txtEntry, txtStatus, cntScrolling, cntButtons)

    winWindow.Resize(fyne.NewSize(1200, 600))
    winWindow.SetContent(cntContent)

    go func() {
        for {
            select {
            case strMessage := <-chnSendMessageToClientWindow:
                txtResults.SetText(strings.TrimPrefix(txtResults.Text()+"\n"+strMessage, "\n"))
                cntScrolling.Refresh()
            }
        }
    }()

    winWindow.ShowAndRun()

Solution

  • You’re probably looking for cntScrolling.ScrollToBottom() When you wrap items in a scroll container there is no way to automatically scroll down or right when new content is added, but that line will do that each time you add content.

    I haven't found a way to "lock" resizing

    Items in fyne are typically either minimum size (pack the content) or expand to fill the space. It is unwise to “lock size” somewhere in between because then the UI does not scale well across screens and window sizes.