2016-11-23 73 views
1

(這是我的第一篇文章,如果對不起,我做錯了什麼......)Gtk.DrawingArea空當連接到Gtk.Grid

我在瓦拉寫一個程序,使用它可以設計一個教室。 我決定使用GUI(Vala與此完美集成), 和Cairo繪製教室圖(GTK默認帶有這個)。

我創建了一個「課堂」類(Gtk.DrawingArea的子類), 目前應該只是顯示一個正方形:

public class Classroom : DrawingArea 
{ 
    private delegate void DrawMethod(); 

    public Classroom() 
    { 
     this.draw.connect((widget, context) => { 
      return draw_class(widget, context, context.stroke); 
      }); 
    } 

    bool draw_class(Widget widget, Context context, DrawMethod draw_method) 
    { 
     context.set_source_rgb(0, 0, 0); 
     context.set_line_width(8); 
     context.set_line_join (LineJoin.ROUND); 

     context.save(); 

     context.new_path(); 
     context.move_to(10, 10); 
     context.line_to(30, 10); 
     context.line_to(30, 30); 
     context.line_to(10, 30); 
     context.line_to(10, 10); 
     context.close_path(); 

     draw_method(); // Actually draw the lines in the buffer to the widget 

     context.restore(); 

     return true; 
    } 
} 

我也創建了一個類爲我的應用程序:

public class SeatingPlanApp : Gtk.Application 
{ 
    protected override void activate() 
    { 
     var root = new Gtk.ApplicationWindow(this); 
     root.title = "Seating Plan"; 
     root.set_border_width(12); 
     root.destroy.connect(Gtk.main_quit); 

     var grid = new Gtk.Grid(); 
     root.add(grid); 

     /* Make our classroom area */ 
     var classroom = new Classroom(); 
     grid.attach(classroom, 0, 0, 1, 1); 
     //root.add(classroom); 

     root.show_all(); 
    } 

    public SeatingPlanApp() 
    { 
     Object(application_id : "com.github.albert-tomanek.SeatingPlan"); 
    } 
} 

這是我的主要功能:

int main (string[] args) 
{ 
    return new SeatingPlanApp().run(args); 
} 

我把我的classroom小部件轉換爲Gtk.Grid,這是我選擇的佈局小部件。 當我編譯我的代碼並運行它,我得到了一個空白窗口:

My blank window

但是,如果我不使用Gtk.Grid,只是加我classroom使用root.add()(我註釋掉)時, classroom小部件正確顯示:

When it works, without using Gtk.Grid

爲什麼使用Gtk.Grid加入時我的小工具顯示不出來?

我能做些什麼來解決這個問題?

+0

歡迎來到SO,你的問題相當好。我做了一些編輯(內聯圖像並刪除了「感謝」部分,這在這裏被認爲是不必要的)。 –

+0

雖然有一件小事:我將所有代碼複製到'.vala'文件並嘗試編譯,但是缺少'使用Gtk;'和'使用Cairo;'指令。下一次您應該考慮將所有必要指令的所有代碼放在一個代碼塊中。 –

+0

就我個人而言,我不喜歡''使用'指令,我只是使用它的完整名稱空間來限定每個類型(GLib名稱空間和我自己的類所在的名稱空間除外)。 –

回答

1

問題是單元格大小爲0x0像素,因爲網格不知道您的繪圖區域實際需要多少空間。

一個簡單的解決方法就是請一些固定的大小,試試這個:

var classroom = new Classroom(); 
classroom.set_size_request (40, 40); 

PS:我通過SO,特別this one尋找其他類似的問題得到了這個想法。

+1

更好的解決方案是將widget設置爲展開/對齊,參見[this](https://developer.gnome.org/gtk3/stable/ch30s02.html)。一個更好的解決方案,但更困難的是,將子類GtkDrawingArea並覆蓋get_preferred_width()和get_preferred_height()方法來返回size *應該是的大小。 – andlabs