Contenu | Rechercher | Menus

Annonce

Si vous avez des soucis pour rester connecté, déconnectez-vous puis reconnectez-vous depuis ce lien en cochant la case
Me connecter automatiquement lors de mes prochaines visites.

À propos de l'équipe du forum.

#1 Le 11/08/2008, à 09:08

jde3

[Résolu] Python, GTK et Glade : problème de treeview

Bonjour,

Je me mets doucement à python et je souhaite réaliser une interface graphique.

Pour cela, j'ai choisi d'utiliser GTK en dessinant mes fenêtres dans glade.

Je souhaite utiliser un treeview pour afficher une liste d'éléments dans mon interface, mais seule la dernière colonne s'affiche.

Voici le code généré par glade :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE glade-interface SYSTEM "glade-2.0.dtd">
<!--Generated with glade3 3.4.5 on Fri Aug  1 17:18:12 2008 -->
<glade-interface>
  <widget class="GtkWindow" id="mainWindow">
    <property name="visible">True</property>
    <property name="default_width">400</property>
    <property name="default_height">200</property>
    <signal name="delete_event" handler="delete"/>
    <child>
      <widget class="GtkVBox" id="vbox1">
        <property name="visible">True</property>
        <property name="homogeneous">True</property>
        <child>
          <widget class="GtkTreeView" id="treeview1">
            <property name="visible">True</property>
            <property name="can_focus">True</property>
            <property name="headers_clickable">True</property>
            <property name="fixed_height_mode">True</property>
          </widget>
        </child>
        <child>
          <widget class="GtkHBox" id="hbox1">
            <property name="visible">True</property>
            <child>
              <widget class="GtkButton" id="button1">
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="label" translatable="yes">Play</property>
                <property name="response_id">0</property>
                <signal name="clicked" handler="on_button1_clicked"/>
              </widget>
            </child>
            <child>
              <widget class="GtkButton" id="button2">
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="label" translatable="yes">Stop</property>
                <property name="response_id">0</property>
                <signal name="clicked" handler="on_button2_clicked"/>
              </widget>
              <packing>
                <property name="position">1</property>
              </packing>
            </child>
            <child>
              <widget class="GtkButton" id="button3">
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="label" translatable="yes">Colorize</property>
                <property name="response_id">0</property>
                <signal name="clicked" handler="on_button3_clicked"/>
              </widget>
              <packing>
                <property name="position">2</property>
              </packing>
            </child>
          </widget>
          <packing>
            <property name="position">1</property>
          </packing>
        </child>
      </widget>
    </child>
  </widget>
</glade-interface>

et mon code python :

#!/usr/bin/python

import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade

class EasyList:
	def __init__(self, treeview, columns, coltypes):		
		if len(columns) != len(coltypes) or len(columns) == 0:
			raise ValueError, "columns and coltypes should be equal in size."
		
		self.treeview = treeview
		self.store = gtk.ListStore(*coltypes)
		self.cellr = gtk.CellRendererText()
		
		for count,column in zip(xrange(len(columns)), columns):
			current = gtk.TreeViewColumn(column, self.cellr)
			current.add_attribute(self.cellr, "text", count)
			current.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
			self.treeview.append_column(current)
		
		self.treeview.set_model(self.store)
	
	def append_row(self, data):
		if type(data) is not list and type(data) is not tuple:
			data = (data,)
		self.store.append(data)


class myGUI:
	def __init__(self):
		self.widgets = gtk.glade.XML('showList.glade',"mainWindow")
		self.widgets.get_widget("mainWindow").set_title("Evaluation GUI")
		self.autoConnect()
		
		self._gtklist = EasyList(self.widgets.get_widget("treeview1"), ("OK", "Filename", "Chunk ID", "Distance"), (str, str, str, int))
		self._gtklist.append_row(("Test1", "Value1", "Value 1b", 0))
		self._gtklist.append_row(("Test2", "Value2", "Value 2b", 1))

	def autoConnect(self):
		eventHandlers = {}
		for (itemName,value) in self.__class__.__dict__.items():
			if callable(value) and itemName.startswith('gtk_'):
				eventHandlers[itemName[4:]] = getattr(self,itemName)
		self.widgets.signal_autoconnect(eventHandlers)

	def __getitem__(self, key):
		return self.widgets.get_widget(key)

	def gtk_delete(self, source=None, event=None):
		gtk.main_quit()

	def gtk_on_button1_clicked(self, source=None, event=None):
		self['button1'].set_text("Test")
		return True

	def gtk_on_button2_clicked(self, source=None, event=None):
		return True

	def gtk_on_button3_clicked(self, source=None, event=None):
		return True

if __name__ == '__main__':
	app = myGUI()
	gtk.main()

Sauriez-vous me dire pourquoi toutes les colonnes ne veulent pas s'afficher les unes à côté des autres ?

Merci d'avance.

Dernière modification par jde3 (Le 11/08/2008, à 10:29)

Hors ligne

#2 Le 11/08/2008, à 10:29

jde3

Re : [Résolu] Python, GTK et Glade : problème de treeview

Problème auto-résolu en fouillant dans les méthodes de gtk.TreeViewColumn et en modifiant mon code python comme suit (spécification de la taille mini des colonnes dans le constructeur de la classe EasyList) :

#!/usr/bin/python

import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade

class EasyList:
	def __init__(self, treeview, columns, coltypes, colsizes):
		if len(columns) != len(coltypes) or len(columns) != len(colsizes) or len(columns) == 0:
			raise ValueError, "columns, coltypes and colsizes should be equal in size."
		
		self.treeview = treeview
		self.store = gtk.ListStore(*coltypes)
		self.cellr = gtk.CellRendererText()
		
		for count,column in zip(xrange(len(columns)), columns):
			current = gtk.TreeViewColumn(column, self.cellr)
			current.add_attribute(self.cellr, "text", count)
			current.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
			current.set_resizable(True)
			current.set_min_width(colsizes[count])
			self.treeview.append_column(current)
		
		self.treeview.set_model(self.store)
	
	def append_row(self, data):
		if type(data) is not list and type(data) is not tuple:
			data = (data,)
		self.store.append(data)


class myGUI:
	def __init__(self):
		self.widgets = gtk.glade.XML('showList.glade',"mainWindow")
		self.widgets.get_widget("mainWindow").set_title("Evaluation GUI")
		self.autoConnect()
		
		self._gtklist = EasyList(self.widgets.get_widget("treeview1"), ("OK", "Filename", "Chunk ID", "Distance"), (str, str, str, int), (70, 70, 70, 70))
		self._gtklist.append_row(("Test1", "Value1", "Value 1b", 0))
		self._gtklist.append_row(("Test2", "Value2", "Value 2b", 1))

	def autoConnect(self):
		eventHandlers = {}
		for (itemName,value) in self.__class__.__dict__.items():
			if callable(value) and itemName.startswith('gtk_'):
				eventHandlers[itemName[4:]] = getattr(self,itemName)
		self.widgets.signal_autoconnect(eventHandlers)

	def __getitem__(self, key):
		return self.widgets.get_widget(key)

	def gtk_delete(self, source=None, event=None):
		gtk.main_quit()

	def gtk_on_button1_clicked(self, source=None, event=None):
		self['button1'].set_text("Test")
		return True

	def gtk_on_button2_clicked(self, source=None, event=None):
		return True

	def gtk_on_button3_clicked(self, source=None, event=None):
		return True

if __name__ == '__main__':
	app = myGUI()
	gtk.main()

Je ne sais pas s'il y a plus élégant (dans l'idéal, j'aimerais que les colonnes prennent, par exemple, juste la taille nécessaire pour écrire leur nom dans le titre de colonne), si oui, faites-moi signe...

Hors ligne