2012-08-31 56 views
5

我正在嘗試創建一個帶有標籤的不可調整大小的對話框。這個標籤有很多文字,所以我想讓它在換行時沒有讓對話變得很寬GTK標籤包裝在對話框中

出於某種原因,我找不到讓GTK允許這種情況發生的原因。我甚至找不到在對話框中設置最大寬度的方法,這將非常棒。

這裏是我的意思的運行例如:

#!/usr/bin/env python 
#-*- coding:utf-8 -*- 

from gi.repository import Gtk 

class DialogExample(Gtk.Dialog): 

    def __init__(self, parent): 
     Gtk.Dialog.__init__(self, "My Dialog", parent, 0, 
      (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, 
      Gtk.STOCK_OK, Gtk.ResponseType.OK)) 

     self.set_default_size(150, 100) 
     self.set_resizable(False) 

     label = Gtk.Label("This is a dialog to display additional information, with a bunch of text in it just to make sure it will wrap enough for demonstration purposes") 
     label.set_line_wrap(True) 

     box = self.get_content_area() 
     box.add(label) 
     self.show_all() 

class DialogWindow(Gtk.Window): 

    def __init__(self): 
     Gtk.Window.__init__(self, title="Dialog Example") 

     self.set_default_size(250, 200) 


     button = Gtk.Button("Open dialog") 
     button.connect("clicked", self.on_button_clicked) 

     self.add(button) 

    def on_button_clicked(self, widget): 
     dialog = DialogExample(self) 
     response = dialog.run() 

     if response == Gtk.ResponseType.OK: 
      print "The OK button was clicked" 
     elif response == Gtk.ResponseType.CANCEL: 
      print "The Cancel button was clicked" 

     dialog.destroy() 

win = DialogWindow() 
win.connect("delete-event", Gtk.main_quit) 
win.show_all() 
Gtk.main() 

回答

5

我解決了這個(除了設置自動換行至真)把Gtk.Label一個Gtk.Table內,使用填充和收縮標誌和爲標籤設置固定寬度。事情是這樣的:

label = Gtk.Label("This is a dialog to display additional information, with a bunch of text in it just to make sure it will wrap enough for demonstration purposes") 
label.set_line_wrap(True) 
label.set_size_request(250, -1) # 250 or whatever width you want. -1 to keep height automatic 

table = Gtk.Table(1, 1, False) 
table.attach(label, 0, 1, 0, 1, Gtk.AttachOptions.SHRINK | Gtk.AttachOptions.FILL) 

這應該做的伎倆

+0

挖了一點點,我意識到這是什麼問題。當你創建窗口/對話框時,第一次標籤沒有顯示父容器大小參考,因此Gtk將盡可能多的空間分配給標籤,然後設置父寬度,從而產生一個巨大的窗口。 爲了避免這種情況,請設置父級的首選寬度並進行顯示,這樣Gtk就計算父級幾何體,並且標籤將具有父級大小的真實參考。我這樣做了,現在一切都像魅力一樣工作。 – satanas

+0

hi @satanas - 你有什麼機會可以進一步描述你如何「爲父母設置首選寬度並進行表演」?我有同樣的問題; Gtk.Table選項從v3.4開始已被棄用,所以我正在尋找一個不被棄用的解決方案。 TIA – fossfreedom