方向
GTK+ 中的许多小部件可以水平或垂直定向。从分隔符到工具栏的任何东西都在实现 GtkOrientable 接口,以便通过设置 ::orientation 属性在运行时更改此设置。因此,很明显,GtkCenterBox 也应该遵循这种模式。
我不会详细解释如何添加接口和实现属性。对我们来说,有趣的部分是我们将如何在尺寸分配期间使用 orientation 属性。
值得庆幸的是,我们的大部分机制已经用单个维度编写,并且可以像宽度一样应用于高度。剩下的就是遍历所有函数,并确保在执行任何依赖于方向的操作时考虑方向。例如,我们引入一个小助手来查询正确的 expand 属性。
static gboolean get_expand (GtkWidget *widget, GtkOrientation orientation) { if (orientation == GTK_ORIENTATION_HORIZONTAL) return gtk_widget_get_hexpand (widget); else return gtk_widget_get_vexpand (widget); }
需要记住的一件事是,我们在此处实现的一些功能仅适用于水平方向,例如从右到左翻转或基线。
measure() 函数更改以避免硬编码水平方向
if (orientation == self->orientation) gtk_center_box_measure_orientation (widget, orientation, for_size, minimum, natural, min_baseline, nat_baseline); else gtk_center_box_measure_opposite (widget, orientation, for_size, minimum, natural, min_baseline, nat_baseline);
size_allocate() 函数调用 distribute() 来根据方向分配宽度或高度
if (self->orientation == GTK_ORIENTATION_HORIZONTAL) { size = width; for_size = height; } else { size = height; for_size = width; } distribute (self, for_size, size, sizes);
在这些直接但繁琐的更改之后,我们可以垂直定向中心框
只想花点时间快速感谢您抽出时间撰写这些文章。有很多关于 GTK 入门的信息。似乎缺少或难以追踪的是关于使用它做更复杂事情的信息。