python - PyGObject 模板子未定义
问题描述
我已经为我的 GTK 项目创建了一个 Glade UI,其规范如下:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.22.1 -->
<interface>
<requires lib="gtk+" version="3.20"/>
<template class="Pages" parent="GtkBox">
<property name="visible">True</property>
<property name="can_focus">False</property>
<child>
<object class="GtkLabel" id="page_title">
<property name="visible">True</property>
<property name="label" translatable="yes">Title</property>
<attributes>
<attribute name="weight" value="normal"/>
<attribute name="scale" value="1.5"/>
</attributes>
</object>
<packing>
<property name="expand">True</property>
<property name="fill">True</property>
</packing>
</child>
</template>
</interface>
这个 Glade UI 链接在另一个 UI 中,该 UI 在应用程序首次启动时默认运行。
按照这里提到的API ,我尝试page_title
在python实现中引用标签:
from gi.repository import Gtk
@Gtk.Template(resource_path='/com/bscubed/App/ui/pages.ui')
class Pages(Gtk.Box):
__gtype_name__ = 'Pages'
page_title = Gtk.Template.Child()
def __init__(self, **kwargs):
super().__init__(**kwargs)
print(type(self.page_title))
self.page_title.set_text("Test")
但是输出总是
<class 'gi._gtktemplate.Child'>
AttributeError: 'Child' object has no attribute 'set_text'
而且我无法访问标签通常可用的任何方法。
但是,模板定义在主窗口实现中工作得很好:
from gi.repository import Gtk
from .pages import Pages
@Gtk.Template(resource_path='/com/bscubed/App/ui/window.ui')
class MainWindow(Gtk.ApplicationWindow):
__gtype_name__ = 'MainWindow'
toolbar_stack = Gtk.Template.Child()
content_stack = Gtk.Template.Child()
start_button = Gtk.Template.Child()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.start_button.connect("clicked", self.next_page)
print(type(self.start_button))
def next_page(self, button):
self.content_stack.set_visible_child_name("pages")
self.toolbar_stack.set_visible_child_name("pages_toolbar")
的输出是<class 'gi.overrides.Gtk.Button'>
所以 PyGObject 发生了一些非常奇怪的事情。难道我做错了什么?任何帮助表示赞赏,并提前感谢您。
解决方案
使用GtkTemplate.Child()
而不是Gtk.Template.Child()
.
编辑:Gtk.Template.Child()
仅适用于最新的 GTK+ 3 版本。您应该将其更新到最新版本,或者,您可以GtkTemplate.Child()
在gi_composites.py
补丁文件中使用。
有关更多信息,请阅读目录gi_composites.py
中第 162 行的文档/your_project/src