我正在尝试实现一个文本视图,当用户单击它时,它将选中所有文本。但是,当我尝试执行以下操作时,虽然在拖动窗口后选择了文本视图,但在单击文本视图时不会选择该文本。
考虑这个最小的例子:

#include <gtk/gtk.h>
gboolean cb(GtkWidget *tv, GdkEvent *event, gpointer user_data) {
    GtkTextBuffer *buf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(tv));
    GtkTextIter start, end;
    gtk_text_buffer_get_start_iter(buf, &start);
    gtk_text_buffer_get_end_iter(buf, &end);
    gtk_text_buffer_select_range(buf, &start, &end);
    return FALSE;
}

int main(int argc, char *argv[]) {
    gtk_init(&argc, &argv);
    GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    GtkWidget *box1 = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
    gtk_container_add(GTK_CONTAINER(window), box1);

    GtkWidget *tv1 = gtk_text_view_new();
    GtkWidget *tv2 = gtk_text_view_new();
    gtk_box_pack_start(GTK_BOX(box1), tv1, TRUE, TRUE, 0);
    gtk_box_pack_start(GTK_BOX(box1), tv2, TRUE, TRUE, 0);

    GtkTextBuffer *buf1 = gtk_text_view_get_buffer(GTK_TEXT_VIEW(tv1));
    GtkTextBuffer *buf2 = gtk_text_view_get_buffer(GTK_TEXT_VIEW(tv2));
    gtk_text_buffer_set_text(buf1, "asdf", -1);
    gtk_text_buffer_set_text(buf2, "ghjkl", -1);

    g_signal_connect(tv2, "focus-in-event", G_CALLBACK(cb), NULL);

    gtk_widget_show(tv1);
    gtk_widget_show(tv2);
    gtk_widget_show(box1);
    gtk_widget_show(window);
    gtk_main();
    return 0;
}

我应该改变什么才能得到想要的结果?

最佳答案

改为将回调函数连接到button-release-event

10-06 11:26