kit de ferramentas GUI Python de nível superior, por exemplo dict de aprovação para TreeView / Grid
Iniciei meu primeiro projeto de estimação em Python usando PyGTK. Embora seja um kit de ferramentas da GUI realmente poderoso e tenha uma excelente aparência, tenho algumas irritações. Então, pensei em fazer a transição para outra coisa, pois ainda não é muito extensa. Deu uma olhada emTÃO edocumentação python, mas não obteve uma boa visão geral.
O que é legal no PyGTK:
Arquivos Gladeself.signal_autoconnect ({...})self.get_widget () como __getattr__Isso está me incomodando no entanto:
manual gobject.idle_add (lambda: ... and False)nenhuma funcionalidade padrão para salvar estados de aplicativos / janelasO TreeView precisa de construção de arraywidget.get_selection (). get_selected (), model.get_value (iter, liststore_index)TreeView: Como esse é o principal elemento da interface, é o mais perturbador. Basicamente, meu aplicativo cria uma lista de dicionários a serem exibidos name = column + row => value. Para exibi-lo usando o GTK, é necessário que haja um processo de conversão manual, pedidos e previsões. Isso parece muita sobrecarga, e eu desejei algo mais orientado a objetos aqui. O PyGtk possui muitas abstrações no topo do gtk +, mas ainda parece um pouco de baixo nível. Eu preferiria passar meu ditado como está e ter colunas predefinidas de alguma forma. (O GtkBuilder pode predefinir as colunas do TreeView, mas isso não resolve a sobrecarga da representação de dados.)
Quando recebo um clique na minha lista do TreeView, também preciso converter tudo de volta nas estruturas de dados do meu aplicativo. E também é incômodo que o PyGTK não atenda as chamadas gtk + com o próprio gobject.idle, se executado a partir de um thread não principal. No momento, há muito código da GUI que acredito que não deveria ser necessário ou que poderia ser racionalizado.
? Então, existem invólucros adicionais no PyGTK. Ou qual outro kit de ferramentas suporta interfaces mais simples para exibir um Grid / TreeView. Eu li muito sobre o wxPython ser o favorito de todos, mas é menos maduro no Linux. EPyQT parece ser basicamente o mesmo nível de abstração que o PyGTK. Não useiTkInter muito, portanto, não sei se ele possui interfaces mais simples, mas parece pouco atraente. Como fazPyFLTK. O pijama parece fascinante, mas já está muito longe (aplicativo de desktop).
.
Então, kit de ferramentas da GUI com dict -> Grid display. Qual você escolheria?
.
Assim como a exibição, esta é minha função de mapeamento TreeView atual. Tipo de obras, mas eu preferiria ter algo padrão:
#-- fill a treeview
#
# Adds treeviewcolumns/cellrenderers and liststore from a data dictionary.
# Its datamap and the table contents can be supplied in one or two steps.
# When new data gets applied, the columns aren't recreated.
#
# The columns are created according to the datamap, which describes cell
# mapping and layout. Columns can have multiple cellrenderers, but usually
# there is a direct mapping to a data source key from entries.
#
# datamap = [ # title width dict-key type, renderer, attrs
# ["Name", 150, ["titlerow", str, "text", {} ] ],
# [False, 0, ["interndat", int, None, {} ] ],
# ["Desc", 200, ["descriptn", str, "text", {} ], ["icon",str,"pixbuf",{}] ],
#
# An according entries list then would contain a dictionary for each row:
# entries = [ {"titlerow":"first", "interndat":123}, {"titlerow":"..."}, ]
# Keys not mentioned in the datamap get ignored, and defaults are applied
# for missing cols. All values must already be in the correct type however.
#
@staticmethod
def columns(widget, datamap=[], entries=[], pix_entry=False):
# create treeviewcolumns?
if (not widget.get_column(0)):
# loop through titles
datapos = 0
for n_col,desc in enumerate(datamap):
# check for title
if (type(desc[0]) != str):
datapos += 1 # if there is none, this is just an undisplayed data column
continue
# new tvcolumn
col = gtk.TreeViewColumn(desc[0]) # title
col.set_resizable(True)
# width
if (desc[1] > 0):
col.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED)
col.set_fixed_width(desc[1])
# loop through cells
for var in xrange(2, len(desc)):
cell = desc[var]
# cell renderer
if (cell[2] == "pixbuf"):
rend = gtk.CellRendererPixbuf() # img cell
if (cell[1] == str):
cell[3]["stock_id"] = datapos # for stock icons
expand = False
else:
pix_entry = datapos
cell[3]["pixbuf"] = datapos
else:
rend = gtk.CellRendererText() # text cell
cell[3]["text"] = datapos
col.set_sort_column_id(datapos) # only on textual cells
# attach cell to column
col.pack_end(rend, expand=cell[3].get("expand",True))
# apply attributes
for attr,val in cell[3].iteritems():
col.add_attribute(rend, attr, val)
# next
datapos += 1
# add column to treeview
widget.append_column(col)
# finalize widget
widget.set_search_column(2) #??
widget.set_reorderable(True)
# add data?
if (entries):
#- expand datamap
vartypes = [] #(str, str, bool, str, int, int, gtk.gdk.Pixbuf, str, int)
rowmap = [] #["title", "desc", "bookmarked", "name", "count", "max", "img", ...]
if (not rowmap):
for desc in datamap:
for var in xrange(2, len(desc)):
vartypes.append(desc[var][3]) # content types
rowmap.append(desc[var][0]) # dict{} column keys in entries[] list
# create gtk array storage
ls = gtk.ListStore(*vartypes) # could be a TreeStore, too
# prepare for missing values, and special variable types
defaults = {
str: "",
unicode: u"",
bool: False,
int: 0,
gtk.gdk.Pixbuf: gtk.gdk.pixbuf_new_from_data("\0\0\0\0",gtk.gdk.COLORSPACE_RGB,True,8,1,1,4)
}
if gtk.gdk.Pixbuf in vartypes:
pix_entry = vartypes.index(gtk.gdk.Pixbuf)
# sort data into gtk liststore array
for row in entries:
# generate ordered list from dictionary, using rowmap association
row = [ row.get( skey , defaults[vartypes[i]] ) for i,skey in enumerate(rowmap) ]
# autotransform string -> gtk image object
if (pix_entry and type(row[pix_entry]) == str):
row[pix_entry] = gtk.gdk.pixbuf_new_from_file(row[pix_entry])
# add
ls.append(row) # had to be adapted for real TreeStore (would require additional input for grouping/level/parents)
# apply array to widget
widget.set_model(ls)
return ls
pass