2016-02-19 51 views
0

这是练习的一部分。我在SO上找不到类似的问题。这里有一个小小的GTK程序,点击重命名按钮后,文件应该重命名。无法重命名文件,因为:g_file_set_display_name:assertion'G_IS_FILE(file)'failed

虽然uri似乎指向正确的文件,但出于某种原因,我得到断言G_IS_FILE在运行时失败。

下面是代码:

[indent=4] 
uses 
    Gtk 

class TestWindow:Window 
    _file_chooser:FileChooserButton 
    _entry:Gtk.Entry 
    _button:Gtk.Button 
    _file:File 

    construct() 
     title = "File chooser" 
     window_position = WindowPosition.CENTER 
     destroy.connect(Gtk.main_quit) 
     var folder_chooser = new FileChooserButton("Choose a Folder",FileChooserAction.SELECT_FOLDER) 
     folder_chooser.set_current_folder(Environment.get_home_dir()) 

     //I used selection_changed directly as per the question in stack_exchange 
     //http://stackoverflow.com/questions/34689763/the-signal-connect-syntax 
     folder_chooser.selection_changed.connect(folder_changed) 

     _file_chooser = new FileChooserButton("Choose a File",FileChooserAction.OPEN) 
     _file_chooser.set_current_folder(Environment.get_home_dir()) 

     _file_chooser.file_set.connect(file_changed) 
     _entry = new Gtk.Entry() 
     _entry.set_text("Here the file name") 
     //_entry.activate.connect(name_altered) 

     _button = new Button.with_label("Rename") 
     _button.set_sensitive(false) 
     _button.clicked.connect(btn_pressed) 

     var box = new Box(Orientation.VERTICAL, 0) 
     box.pack_start(folder_chooser, true, true, 0) 
     box.pack_start(_file_chooser, true, true, 0) 
     box.pack_start(_entry, true, true, 0) 
     box.pack_start(_button, true, true, 0) 
     add(box) 

    def folder_changed(folder_chooser_widget:FileChooser) 
     folder:string = folder_chooser_widget.get_uri() 
     _file_chooser.set_current_folder_uri(folder) 

    def file_changed (file_chooser_widget: FileChooser) 
     _file:File = File.new_for_uri(file_chooser_widget.get_uri()) 

     try 
      info:FileInfo = _file.query_info (FileAttribute.ACCESS_CAN_WRITE, FileQueryInfoFlags.NONE, null) 
      writable: bool = info.get_attribute_boolean (FileAttribute.ACCESS_CAN_WRITE) 
      if !writable 
       _entry.set_sensitive (false) 
      else 
       _button.set_sensitive (true) 
     except e: Error 
      print e.message 

     _entry.set_text(_file.get_path()) 

    def btn_pressed() 
     _file.set_display_name(_entry.get_text()) 

init 
    Gtk.init(ref args) 
    var test = new TestWindow() 
    test.show_all() 
    Gtk.main() 

问题出现在行:_file.set_display_name(_entry.get_text())。我正在寻找一些关于我在这个小巧精灵代码中做错了什么的见解。

回答

2

_file当您致电_file.set_display_name()时为空。问题就在这里:

_file:File = File.new_for_uri(file_chooser_widget.get_uri()) 

你会创建一个名为_file新的变量,它屏蔽了该_file领域。将其更改为

_file = File.new_for_uri(file_chooser_widget.get_uri()) 

应解决此问题。请注意,您也可以使用this._field来访问该字段;键入时间稍长一些,但更易于阅读,并且使得这样的错误更加明显。

+0

谢谢nemequ,你可以建议一些参考,我可以学习如何使用this._field? –