Я хочу использовать GTK в программе Julia для отображения списка свойств, которые меняются со временем. Я сейчас и к ГТК и к Юле
Я попытался объединить учебник для составных виджетов с тот для списка, но это не сработало, так как я получаю ошибки, когда пытаюсь получить доступ к ListStore извне структуры.
Для моей конкретной цели мне даже не нужно нажимать на listStore. Было бы достаточно, если бы я мог изменить строки, которые уже есть. Кроме того, я все еще нахожусь на ранней стадии разработки, поэтому я все еще могу перейти на другую графическую среду, поэтому рекомендации также приветствуются.
Следующее работает, пока я не пытаюсь получить доступ к myListStore
.
using Gtk
mutable struct CustomStore <: Gtk.GtkListStore
handle::Ptr{Gtk.GObject}
listStore
# listStore::Gtk.GtkListStoreLeaf
# listStore::Ptr{Gtk.GObject}
function CustomStore()
container = GtkBox(:v)
infoLabel= GtkLabel("container")
push!(container, infoLabel)
listStore = GtkListStore(String, Int)
push!(listStore,("aaa",123))
push!(listStore,("bbb",234))
print("typeof(listStore): ")
println(typeof(listStore)) # typeof(listStore): GtkListStoreLeaf
tv = GtkTreeView(GtkTreeModel(listStore))
rTxt = GtkCellRendererText()
c1 = GtkTreeViewColumn("Name", rTxt, Dict([("text",0)]))
c2 = GtkTreeViewColumn("Value", rTxt, Dict([("text",1)]))
push!(tv, c1, c2)
push!(container,tv)
push!(listStore,("ccc",345))
print("typeof(listStore): ")
println(typeof(listStore)) # typeof(listStore): GtkListStoreLeaf
return Gtk.gobject_move_ref(new(container.handle), container)
end
end
function main()
win = GtkWindow("My First Gtk.jl Program", 800, 600)
myStore = CustomStore()
push!(win, myStore)
showall(win)
# Some things I tried but yielded errors:
# myListStore::GtkTreeStore = getproperty(myStore, :ts)
# myListStore::GtkListStoreLeaf = getproperty(myStore, :ts)
# myListStore = get_gtk_property(myStore,:ts,String)
myListStore = getproperty(myStore, :ts)
print("typeof(myListStore): ")
println(typeof(myListStore)) # typeof(myListStore): Gtk.GLib.FieldRef{CustomStore}
println("Here is what my goal is: Modifying the listStore after the custom widget has been initialized: ")
# push!(myListStore,("zzz",999))
# --> ERROR: LoadError: MethodError: no method matching push!(::Gtk.GLib.FieldRef{CustomStore}, ::Tuple{String, Int64})
# Closest candidates are:
# push!(::Any, ::Any, ::Any) at /opt/julia-1.7.2/share/julia/base/abstractarray.jl:2952
# push!(::Any, ::Any, ::Any, ::Any...) at /opt/julia-1.7.2/share/julia/base/abstractarray.jl:2953
# push!(::GtkTreeStore, ::Tuple) at ~/.julia/packages/Gtk/B6LVT/src/lists.jl:224
if !isinteractive()
@async Gtk.gtk_main()
Gtk.waitforsignal(win,:destroy)
end
end
main()
В вашем конструкторе вы должны вернуть структуру new() в том виде, в каком вы ее объявили: дескриптор и хранилище списка.
Вам также иногда нужно обновить окно после изменения листинга. Скрытие и отображение окна должно делать это:
using Gtk
mutable struct CustomStore <: Gtk.GtkListStore
handle::Ptr{GObject}
listStore::GtkListStoreLeaf
function CustomStore()
container = GtkBox(:v)
infoLabel= GtkLabel("container")
push!(container, infoLabel)
listStore = GtkListStore(String, Int)
push!(listStore,("aaa",123))
push!(listStore,("bbb",234))
print("typeof(listStore): ")
println(typeof(listStore)) # typeof(listStore): GtkListStoreLeaf
tv = GtkTreeView(GtkTreeModel(listStore))
rTxt = GtkCellRendererText()
c1 = GtkTreeViewColumn("Name", rTxt, Dict([("text",0)]))
c2 = GtkTreeViewColumn("Value", rTxt, Dict([("text",1)]))
push!(tv, c1, c2)
push!(container,tv)
push!(listStore,("ccc",345))
print("typeof(listStore): ")
println(typeof(listStore)) # typeof(listStore): GtkListStoreLeaf
return Gtk.gobject_move_ref(new(container.handle, listStore), container)
end
end
function main()
win = GtkWindow("My First Gtk.jl Program", 800, 600)
myStore = CustomStore()
push!(win, myStore)
showall(win)
println("Here is what my goal is: Modifying the listStore after the custom widget has been initialized: ")
push!(myStore.listStore,("zzz",999))
hide(win)
show(win)
if !isinteractive()
@async Gtk.gtk_main()
Gtk.waitforsignal(win,:destroy)
end
end
main()
Ах, да, вы можете. Это рекомендуется, потому что это может помешать сборке мусора ссылки на контейнер в конструкторе вашего кода до тех пор, пока CustomStore не выйдет за рамки. Я отредактирую это здесь.
Благодарю. это работает как шарм, и я кое-чему научился new()
.
Спасибо. До сих пор я не смотрел, как работают конструкторы в julia. У меня есть вопрос, но в документе gtk.jl сказано, что вызов gobject_move_ref необходим для чего-то, чего я не совсем понял. Правильно ли я предполагаю, что могу воссоздать функцию gobject_move_ref просто, обернув в нее новую конструкцию следующим образом:
return Gtk.gobject_move_ref(new(container.handle, listStore), container)
?