LoginSignup
0
0

More than 1 year has passed since last update.

PythonでGtkBuilderScopeを使う

Posted at

以前、「GtkBuilderScopeはどのように使えばいいんだ!?」と言っていて、結論は「別に使わなくていいや」という事になりましたが、別の話で資料を漁っていたらサンプルが見つかったので、せっかくなのでメモっておきます。

要は話は簡単、GtkBuilderScopeを継承した自作クラスを作ればいいわけです。
まぁそのぐらいは検討つけていたけど、create_closureの戻り値はGClosureなんだけど、Pythonの場合どうすればいいの?という点が悩みどころだったのだけど、callableオブジェクトを返せばいいらしい。
(上記の例ではfunctools.partialを使っているけど、なんの意味があるのだろう?使わなくても問題なさそうなんだけど…)

# coding: utf-8

import sys
import gi
gi.require_version('Gtk', '4.0')
from gi.repository import Gtk, GObject

class MyBuilderScope(GObject.GObject, Gtk.BuilderScope):
	__gtype_name__ = 'MyBuilderScope'

	def do_create_closure(self, *args):
		print('do_create_closure(): args = %s.' % repr(args))
		return self.func

	def func(self, *args):
		print('func: args = %s.' % repr(args))

ui = '''
<interface>
	<object class="GtkWindow" id="window">
		<child>
			<object class="GtkButton" id="button">
				<property name="label">Push</property>
				<signal name="clicked" handler="on_clicked" />
			</object>
		</child>
	</object>
</interface>
'''

def on_activate(app):
	builder = Gtk.Builder()
	builder.set_scope(MyBuilderScope())
	builder.add_from_string(ui)

	window = builder.get_object('window')
	window.set_application(app)
	window.show()

if __name__ == '__main__':
	app = Gtk.Application()
	app.connect('activate', on_activate)
	sys.exit(app.run(sys.argv))
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0