以下是Genie中ToolbarButton的工作代码。目标是获取所选文件的uri并将其返回到该类的构造/初始化。问题是,在我遇到的所有示例中,使用了全局_变量(如下面的代码所示)。它看起来不直观,我担心,只要代码变大,删除错误就会变得更加困难,因为这些变量会开始累积。有没有其他的方法让openfile函数将uri返回到类的构造/ init中的常规变量?在Genie中避免全局变量
下面是代码:
uses
Granite.Widgets
Gtk
init
Gtk.init (ref args)
var app = new Application()
app.show_all()
Gtk.main()
// This class holds all the elements from the GUI
class Application : Gtk.Window
_view:Gtk.TextView
_uri:string
construct()
// Prepare Gtk.Window:
this.window_position = Gtk.WindowPosition.CENTER
this.destroy.connect (Gtk.main_quit)
this.set_default_size (400, 400)
// Headerbar definition
headerbar:Gtk.HeaderBar = new Gtk.HeaderBar()
headerbar.show_close_button = true
headerbar.set_title("My text editor")
// Headerbar buttons
open_button:Gtk.ToolButton = new ToolButton.from_stock(Stock.OPEN)
open_button.clicked.connect (openfile)
// Add everything to the toolbar
headerbar.pack_start (open_button)
show_all()
this.set_titlebar(headerbar)
// Box:
box:Gtk.Box = new Gtk.Box (Gtk.Orientation.VERTICAL, 1)
this.add (box)
// A ScrolledWindow:
scrolled:Gtk.ScrolledWindow = new Gtk.ScrolledWindow (null, null)
box.pack_start (scrolled, true, true, 0)
// The TextView:
_view = new Gtk.TextView()
_view.set_wrap_mode (Gtk.WrapMode.WORD)
_view.buffer.text = "Lorem Ipsum"
scrolled.add (_view)
def openfile (self:ToolButton)
var dialog = new FileChooserDialog ("Open file",
this,
FileChooserAction.OPEN,
Stock.OK, ResponseType.ACCEPT,
Stock.CANCEL, ResponseType.CANCEL)
//filter.add_pixbuf_formats()
//dialog.add_filter (filter)
case dialog.run()
when ResponseType.ACCEPT
var filename = dialog.get_filename()
//image.set_from_file(filename)
if (dialog.run() == Gtk.ResponseType.ACCEPT)
_uri = dialog.get_uri()
stdout.printf ("Selection:\n %s", _uri)
dialog.destroy()
或者我不应该担心在所有关于_variables积累?
@AIThomas这让我更加清楚我在Github上阅读的代码!你做了这么好的综合!谢谢! –