以下是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上閱讀的代碼!你做了這麼好的綜合!謝謝! –