如何将键盘焦点放在弹出式Gtk.Window上

时间:2009-12-18 00:36:47

标签: gtk

我有一个弹出窗口(使用WINDOW_POPUP类型创建),其中包含一些小部件,包括文本条目。问题是当我点击它时,条目没有得到焦点,所以我无法输入任何内容。是否有任何标志我必须设置以允许窗口获得键盘焦点?

3 个答案:

答案 0 :(得分:4)

您不能将WINDOW_POPUP用于需要焦点的gtk窗口。相反,你应该使用类型为GTK_WINDOW_TOPLEVEL的GtkWindow并调用下一个函数(或方法)

GtkWindow *result = g_object_new(GTK_TYPE_WINDOW, "type", GTK_WINDOW_TOPLEVEL, NULL);
gtk_widget_set_can_focus(result, TRUE);
gtk_window_set_decorated(GTK_WINDOW(result), FALSE);
gtk_window_set_type_hint(GTK_WINDOW(result), GDK_WINDOW_TYPE_HINT_POPUP_MENU);
gtk_window_set_transient_for(GTK_WINDOW(result), main_top_level_window);

这对我有用......不幸的是,当这个“弹出窗口”被破坏时,窗口列表中的图标会闪烁

答案 1 :(得分:1)

尽管有以前的答案和GTK参考,但在使用GTK_WINDOW_POPUP时可以抓住键盘焦点。您需要连接到“show”事件......

GtkWindow *w = gtk_window_new(GTK_WINDOW_POPUP);
g_signal_connect(G_OBJECT(w), "show", G_CALLBACK(on_window_show), NULL);

...有一个试图抓住键盘的回调:

static void on_window_show(GtkWidget *w, gpointer user_data) {
    /* grabbing might not succeed immediately... */
    while (gdk_keyboard_grab(w->window, FALSE, GDK_CURRENT_TIME) != GDK_GRAB_SUCCESS) {
        /* ...wait a while and try again */
        sleep(0.1);
    }
}

这对我很有用。

答案 2 :(得分:-1)

#include <gtk/gtk.h>

static gboolean delete_event( GtkWidget *widget,
                              GdkEvent  *event,
                              gpointer   data )
{
    g_print ("delete event occurred\n");
    gtk_main_quit ();
    return TRUE;
}

static void destroy( GtkWidget *widget,
                     gpointer   data )
{
    gtk_main_quit ();
}

int main( int   argc,
          char *argv[] )
{
    GtkWidget *window;
    GtkWidget *windowpopup;
    GtkWidget *button;

    gtk_init (&argc, &argv);

    /* create a new window */
    window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    windowpopup = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    gtk_window_set_transient_for(GTK_WINDOW(windowpopup),GTK_WINDOW(window));
    gtk_window_set_destroy_with_parent(GTK_WINDOW(windowpopup),TRUE); 
    gtk_widget_show (windowpopup);

    g_signal_connect (G_OBJECT (window), "delete_event",
              G_CALLBACK (delete_event), NULL);
    g_signal_connect (G_OBJECT (window), "destroy",
              G_CALLBACK (destroy), NULL);

    /* Creates a new button with the label "Hello World". */
    button = gtk_button_new_with_label ("Hello World");

    g_signal_connect_swapped (G_OBJECT (button), "clicked",
                  G_CALLBACK (gtk_widget_destroy),
                              G_OBJECT (window));

    gtk_container_add (GTK_CONTAINER (window), button);

    gtk_widget_show (button);
    gtk_widget_show (window);

    gtk_main ();

    return 0;
}