如何让gtk的gtk_window_set_position工作?

时间:2013-07-26 15:00:30

标签: c gtk

我想使用gtk_window_set_position

设置窗口的位置

但似乎在创建窗口后,gtk_window_set_position将不会生效 我想知道如何在窗口显示后调用gtk_window_set_position,即按钮事件?

1 个答案:

答案 0 :(得分:3)

我刚写了一个实现两种方法的最小工作示例。一种方法使用gtk_window_move和另一种gtk_window_set_position

如果你手头有gtk +参考,代码应该是自我解释的。

#include <gtk/gtk.h>
#include <glib.h>

void
button1_clicked_cb (GtkWidget * widget, GtkWindow * window)
{
    GdkWindow *root;
    gint width, height, rwidth, rheight;

    gtk_window_get_size (window, &width, &height);
    root = gtk_widget_get_root_window (GTK_WIDGET (window));
    gdk_window_get_geometry (root, NULL, NULL, &rwidth,
                             &rheight);

    gtk_window_move (window, (rwidth - width) / 2,
                     (rheight - height) / 2);
}

void
button2_clicked_cb (GtkWidget * widget, GtkWindow * window)
{
    gtk_widget_hide (GTK_WIDGET (window));
    gtk_window_set_position (window, GTK_WIN_POS_CENTER);
    gtk_widget_show_all (GTK_WIDGET (window));
}

int
main (int argc, char *argv[])
{
    GtkWidget *window;
    GtkWidget *box;
    GtkWidget *button1;
    GtkWidget *button2;

    gtk_init (&argc, &argv);

    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

    button1 = gtk_button_new_with_label ("approach 1");
    button2 = gtk_button_new_with_label ("approach 2");

    box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 10);
    gtk_box_pack_start (GTK_BOX (box), button1, TRUE, TRUE,
                        10);
    gtk_box_pack_start (GTK_BOX (box), button2, TRUE, TRUE,
                        10);

    gtk_container_add (GTK_CONTAINER (window), box);
    gtk_widget_show_all (window);

    g_signal_connect (window, "destroy",
                      G_CALLBACK (gtk_main_quit), NULL);
    g_signal_connect (button1, "clicked",
                      G_CALLBACK (button1_clicked_cb),
                      window);
    g_signal_connect (button2, "clicked",
                      G_CALLBACK (button2_clicked_cb),
                      window);

    gtk_main ();

    return 0;
}