Как мне создать многоуровневый TreeView с помощью F #? - PullRequest
4 голосов
/ 16 марта 2010

Я хотел бы отобразить структуру каталогов, используя виджеты Gtk # через F #, но мне трудно понять, как перевести TreeViews в F #. Скажем, у меня была структура каталогов, которая выглядит следующим образом:

Directory1
  SubDirectory1
  SubDirectory2
    SubSubDirectory1
  SubDirectory3
Directory2

Как бы я показал эту древовидную структуру с виджетами Gtk #, используя F #?

EDIT:

Градбот был ответом, на который я надеялся, с несколькими исключениями. Если вы используете ListStore, вы теряете возможность расширять уровни, если вместо этого используете:

let musicListStore = new Gtk.TreeStore([|typeof<String>; typeof<String>|])

вы получаете макет с расширяемыми уровнями. Однако это нарушает вызовы AppendValues, поэтому вам нужно добавить некоторые подсказки для компилятора, чтобы выяснить, какой перегруженный метод использовать:

musicListStore.AppendValues (iter, [|"Fannypack" ; "Nu Nu (Yeah Yeah) (double j and haze radio edit)"|])

Обратите внимание, что столбцы явно передаются в виде массива.

Наконец, вы можете вложить уровни еще дальше, используя ListIter, возвращаемый при добавлении значений

let iter = musicListStore.AppendValues ("Dance")
let subiter = musicListStore.AppendValues (iter, [|"Fannypack" ; "Nu Nu (Yeah Yeah) (double j and haze radio edit)"|])
musicListStore.AppendValues (subiter, [|"Some Dude"; "Some Song"|]) |> ignore

1 Ответ

5 голосов
/ 16 марта 2010

Я не совсем уверен, что вы ищете, но вот переведенный пример из их учебников .Это может помочь вам начать.Изображение взято с учебного сайта .

alt text
Я думаю, что ключом к многоуровневому древовидному представлению является добавление значений к значениям iter в этой строке musicListStore.AppendValues (iter, "Fannypack", "Nu Nu (Yeah Yeah) (double j and haze radio edit)") |> ignore

// you will need to add these references gtk-sharp, gtk-sharp, glib-sharp 
// and set the projects running directory to 
// C:\Program Files (x86)\GtkSharp\2.12\bin\

module SOQuestion

open Gtk
open System

let main() =
    Gtk.Application.Init()

    // Create a Window
    let window = new Gtk.Window("TreeView Example")
    window.SetSizeRequest(500, 200)

    // Create our TreeView
    let tree = new Gtk.TreeView()
    // Add our tree to the window
    window.Add(tree)

    // Create a column for the artist name
    let artistColumn = new Gtk.TreeViewColumn()
    artistColumn.Title <- "Artist"

    // Create the text cell that will display the artist name
    let artistNameCell = new Gtk.CellRendererText()
    // Add the cell to the column
    artistColumn.PackStart(artistNameCell, true)

    // Create a column for the song title
    let songColumn = new Gtk.TreeViewColumn()
    songColumn.Title <- "Song Title"

    // Do the same for the song title column
    let songTitleCell = new Gtk.CellRendererText()
    songColumn.PackStart(songTitleCell, true)

    // Add the columns to the TreeView
    tree.AppendColumn(artistColumn) |> ignore
    tree.AppendColumn(songColumn) |> ignore

    // Tell the Cell Renderers which items in the model to display
    artistColumn.AddAttribute(artistNameCell, "text", 0)
    songColumn.AddAttribute(songTitleCell, "text", 1)

    let musicListStore = new Gtk.ListStore([|typeof<String>; typeof<String>|])

    let iter = musicListStore.AppendValues ("Dance")
    musicListStore.AppendValues (iter, "Fannypack", "Nu Nu (Yeah Yeah) (double j and haze radio edit)") |> ignore

    let iter = musicListStore.AppendValues ("Hip-hop")
    musicListStore.AppendValues (iter, "Nelly", "Country Grammer") |> ignore

    // Assign the model to the TreeView
    tree.Model <- musicListStore

    // Show the window and everything on it
    window.ShowAll()

    // add event handler so Gtk will exit
    window.DeleteEvent.Add(fun _ -> Gtk.Application.Quit())

    Gtk.Application.Run()

[<STAThread>]
main()
...