我试图用GTK3动态地改变窗口的光标,但是gtk_widget_get_parent_window
似乎不起作用。
有人能指出我做错了什么吗谢谢!
// https://developer.gnome.org/gtk3/stable/gtk-getting-started.html
// minimal example
#include <gtk/gtk.h>
static void
activate (GtkApplication* app,
gpointer user_data)
{
GtkWidget *window;
window = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (window), "Window");
gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);
// Here \/\/\/\/\/ .
GdkWindow* w = gtk_widget_get_parent_window(window);
GdkCursor* c = gdk_cursor_new_for_display(gdk_display_get_default(), GDK_WATCH);
gdk_window_set_cursor(w, c);
// /\/\/\/\/\ .
gtk_widget_show_all (window);
}
int
main (int argc,
char **argv)
{
GtkApplication *app;
int status;
app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
status = g_application_run (G_APPLICATION (app), argc, argv);
g_object_unref (app);
return status;
}
(main.exe:16508):Gdk CRITICAL**:Gdk_window_set_cursor:assertion
“GDK_IS_WINDOW(WINDOW)”失败
我正在使用GTK 3.16和msys2
多谢提前。
最佳答案
扩展@andlabs注释
任何更改光标的尝试都需要在小部件被添加到小部件层次结构之后完成,或者用GTK术语realized
。
在为小部件触发gtk_widget_get_parent_window()
事件之前调用gtk_widget_get_window()
甚至realize
都将导致两种情况下的空指针。
像@andlabs一样,将gtk_widget_get_window()
与GtkWindow
结合使用更安全。
解决办法。
static GdkWindow* G_WINDOW = 0;
static GdkCursor* G_CURSOR = 0;
// call after WindowRealize()
void changecursor()
{
assert(G_WINDOW != NULL);
gdk_window_set_cursor(G_WINDOW, G_CURSOR);
}
static void WindowRealize(GtkWidget *window, gpointer data)
{
G_CURSOR_HAND = gdk_cursor_new_for_display(gdk_display_get_default(), GDK_HAND2);
G_WINDOW = gtk_widget_get_window(window);
}
static void activate(GtkApplication* app,gpointer user_data)
{
GtkWidget *window = gtk_application_window_new(app);
...
g_signal_connect(window, "realize", G_CALLBACK(WindowRealize), NULL);
gtk_widget_show_all (window);
}
关于c - 无法使用GTK3更改光标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35396956/