GTK Grid中等号按钮占两行高度并与其他按钮底部对齐的实现
GTK计算器等号按钮双倍高度布局实现方案
不需要更换组件,使用GtkGrid就能完成需求,核心是调整按钮的网格位置与跨度,具体修改如下:
关键修改思路
- 修正网格跨度逻辑:GtkGrid的行列跨度指的是单元格数量,而非像素值。普通按钮设为
1行×1列,等号按钮设为2行×1列,结合gtk_grid_set_row_homogeneous(true)的行高均匀设置,就能让等号高度为普通按钮的两倍。 - 对齐底部位置:将等号按钮的底部行索引与相邻按钮(如加号、0号)设为同一行,确保底部对齐。
修改后的代码片段
替换原代码中按钮布局的部分:
// 底部行(行索引3)布局0、逗号、%、+按钮 zero = gtk_button_new_with_label("0"); g_signal_connect(zero, "clicked", G_CALLBACK(zeroFun), NULL); gtk_grid_attach(GTK_GRID(grid_numbers), zero, 0, 3, 1, 1); // 列0,行3,占1列1行 comma = gtk_button_new_with_label(","); gtk_grid_attach(GTK_GRID(grid_numbers), comma, 1, 3, 1, 1); mod = gtk_button_new_with_label("%"); gtk_grid_attach(GTK_GRID(grid_numbers), mod, 2, 3, 1, 1); plus = gtk_button_new_with_label("+"); gtk_grid_attach(GTK_GRID(grid_numbers), plus, 3, 3, 1, 1); // 等号按钮:列4,行2,占1列2行(覆盖行2和行3),底部与加号、0号对齐 equal = gtk_button_new_with_label("="); gtk_grid_attach(GTK_GRID(grid_numbers), equal, 4, 2, 1, 2); // 行2布局1、2、3、-按钮(示例) one = gtk_button_new_with_label("1"); gtk_grid_attach(GTK_GRID(grid_numbers), one, 0, 2, 1, 1); two = gtk_button_new_with_label("2"); gtk_grid_attach(GTK_GRID(grid_numbers), two, 1, 2, 1, 1); three = gtk_button_new_with_label("3"); gtk_grid_attach(GTK_GRID(grid_numbers), three, 2, 2, 1, 1); minus = gtk_button_new_with_label("-"); gtk_grid_attach(GTK_GRID(grid_numbers), minus, 3, 2, 1, 1); // 继续完成其他按钮布局,行1放4、5、6、×;行0放7、8、9、÷等
说明
- 保持
gtk_grid_set_row_homogeneous(GTK_GRID(grid_numbers), true),确保每行高度一致,等号占2行则高度自动翻倍。 - 行索引从0(最顶部)到3(最底部),等号按钮从行2延伸到行3,刚好覆盖两行,底部与行3的按钮对齐。
内容的提问来源于stack exchange,提问作者silvalogmc
相关产品推荐
相关产品推荐

