如何在Glade中为已创建的TreeView添加指定静态数据?
在Glade中为TreeView添加静态数据的方法
首先明确:Glade的可视化编辑界面不支持直接添加TreeStore的静态数据,但你可以手动编辑生成的UI XML文件来实现,具体步骤如下:
1. 修正CellRenderer与TreeStore列的绑定
你当前的XML里,CellRendererText的text属性是硬编码的固定值,这会导致所有行显示相同内容,需要改成绑定到TreeStore的对应列:
- 对于Name列的CellRenderer,绑定到TreeStore的第0列(name列)
- 对于Age列的CellRenderer,绑定到TreeStore的第1列(age列)
2. 在TreeStore中添加静态数据
在<object class="GtkTreeStore" id="treestore1">节点内,<columns>标签之后添加<data>节点,填入你的静态数据。
修改后的完整XML代码
<?xml version="1.0" encoding="UTF-8"?> <!-- Generated with glade 3.40.0 --> <interface> <requires lib="gtk+" version="3.18"/> <object class="GtkTreeStore" id="treestore1"> <columns> <!-- column-name name --> <column type="string"/> <!-- column-name age --> <column type="int"/> </columns> <!-- 添加静态数据 --> <data> <row> <col id="0">Jane</col> <col id="1">10</col> </row> <row> <col id="0">Tom</col> <col id="1">20</col> </row> <row> <col id="0">Mike</col> <col id="1">30</col> </row> <row> <col id="0">Mary</col> <col id="1">40</col> </row> </data> </object> <object class="GtkWindow" id="MainWindow"> <property name="can-focus">False</property> <property name="title" translatable="yes">Example Window</property> <property name="default-width">480</property> <property name="default-height">240</property> <child> <object class="GtkTreeView"> <property name="visible">True</property> <property name="can-focus">True</property> <property name="model">treestore1</property> <property name="enable-grid-lines">both</property> <child internal-child="selection"> <object class="GtkTreeSelection"/> </child> <child> <object class="GtkTreeViewColumn" id="1"> <property name="resizable">True</property> <property name="sizing">autosize</property> <property name="title" translatable="yes">Name</property> <property name="clickable">True</property> <property name="reorderable">True</property> <property name="sort-indicator">True</property> <child> <object class="GtkCellRendererText"/> <!-- 绑定到name列(第0列) --> <attributes> <attribute name="text">0</attribute> </attributes> </child> </object> </child> <child> <object class="GtkTreeViewColumn" id="2"> <property name="resizable">True</property> <property name="sizing">autosize</property> <property name="title" translatable="yes">Age</property> <property name="clickable">True</property> <property name="reorderable">True</property> <property name="sort-indicator">True</property> <child> <object class="GtkCellRendererText"/> <!-- 绑定到age列(第1列) --> <attributes> <attribute name="text">1</attribute> </attributes> </child> </object> </child> </object> </child> </object> </interface>
关键修改说明
- 移除了CellRendererText的硬编码
text属性,改用<attributes>节点绑定到TreeStore的对应列索引 - 在TreeStore中添加了
<data>节点,每个<row>对应一行数据,<col id="n">对应第n列的值
内容的提问来源于stack exchange,提问作者Damn Vegetables
相关产品推荐
相关产品推荐

