我正在尝试使用带有滚动条的日志文本的GTK构建窗口应用程序。我希望当我按下“发送”按钮时,程序会在日志中添加一条消息,并且当文本大于文本字段时,将放置滚动条以显示文本的底部。使用当前代码,如果我以高于2Hz的频率按下按钮,滚动条将几乎移至底部,如果我按下得更慢,滚动条将完全不移动,并且看不到新消息。>
这是我的代码:
#include <gtk/gtk.h>
#include <iostream>
using namespace std;
GtkWidget *text_box;
GtkTextBuffer *buffer;
GtkTextIter iter;
static void print_hello (GtkWidget *widget, gpointer data){
gtk_text_buffer_insert(buffer, &iter, "hello\n", -1);
gtk_text_buffer_get_end_iter( buffer, &iter );
gtk_text_view_scroll_to_iter(GTK_TEXT_VIEW(text_box), &iter, 0.0, true, 0.0, 1.0);
}
static void activate (GtkApplication *app, gpointer user_data){
GtkWidget *window;
GtkWidget *fixed;
GtkWidget *button1;
GtkWidget *button2;
GtkWidget *scrolled_window;
/* Create a new window */
window = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (window), "UART Transmitter");
gtk_window_set_default_size (GTK_WINDOW (window), 300, 400);
/* Create a Fixed Container */
fixed = gtk_fixed_new ();
gtk_container_add (GTK_CONTAINER (window), fixed);
gtk_widget_show (fixed);
/* Creates new button1*/
button1 = gtk_button_new_with_label ("Send");
gtk_widget_set_size_request(button1, 100 ,50);
g_signal_connect (button1, "clicked",G_CALLBACK (print_hello), (gpointer) fixed);
gtk_fixed_put (GTK_FIXED (fixed), button1, 20, 30);
gtk_widget_show (button1);
gtk_widget_show_all (window);
/* Creates new button2*/
button2 = gtk_button_new_with_label ("Close");
gtk_widget_set_size_request(button2, 100 ,50);
g_signal_connect_swapped (button2, "clicked", G_CALLBACK (gtk_widget_destroy), window);
gtk_fixed_put (GTK_FIXED (fixed), button2, 170, 30);
gtk_widget_show (button2);
/* Creates scroll text field*/
scrolled_window = gtk_scrolled_window_new (NULL, NULL);
gtk_widget_set_size_request(scrolled_window, 260 ,180);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
text_box = gtk_text_view_new();
buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_box));
gtk_text_buffer_get_iter_at_offset(buffer, &iter, 0);
gtk_text_buffer_insert(buffer, &iter, "BIOBUS terminal\n", -1);
gtk_container_add (GTK_CONTAINER (scrolled_window), text_box);
gtk_fixed_put (GTK_FIXED (fixed), scrolled_window, 20, 200);
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;
}
为什么不将滚动条放在底部?我该如何解决?