我有一个按钮,当点击时复制并将GtkEntry小部件中的文本附加到GtkTextView小部件中。 (此代码是 GTK +开发基础的“文本视图小部件”一章中的示例的修改版本。)
我希望在复制和附加的文本之前插入一个换行符,这样每行文本都将在GtkTextView小部件中独占一行。我该怎么做?我是GTK +的新手。
以下是代码示例:
#include <gtk/gtk.h>
typedef struct
{
GtkWidget *entry, *textview;
} Widgets;
static void insert_text (GtkButton*, Widgets*);
int main (int argc,
char *argv[])
{
GtkWidget *window, *scrolled_win, *hbox, *vbox, *insert;
Widgets *w = g_slice_new (Widgets);
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_title (GTK_WINDOW (window), "Text Iterators");
gtk_container_set_border_width (GTK_CONTAINER (window), 10);
gtk_widget_set_size_request (window, -1, 200);
w->textview = gtk_text_view_new ();
w->entry = gtk_entry_new ();
insert = gtk_button_new_with_label ("Insert Text");
g_signal_connect (G_OBJECT (insert), "clicked",
G_CALLBACK (insert_text),
(gpointer) w);
scrolled_win = gtk_scrolled_window_new (NULL, NULL);
gtk_container_add (GTK_CONTAINER (scrolled_win), w->textview);
hbox = gtk_hbox_new (FALSE, 5);
gtk_box_pack_start_defaults (GTK_BOX (hbox), w->entry);
gtk_box_pack_start_defaults (GTK_BOX (hbox), insert);
vbox = gtk_vbox_new (FALSE, 5);
gtk_box_pack_start (GTK_BOX (vbox), scrolled_win, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 0);
gtk_container_add (GTK_CONTAINER (window), vbox);
gtk_widget_show_all (window);
gtk_main();
return 0;
}
/* Insert the text from the GtkEntry into the GtkTextView. */
static void
insert_text (GtkButton *button,
Widgets *w)
{
GtkTextBuffer *buffer;
GtkTextMark *mark;
GtkTextIter iter;
const gchar *text;
buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (w->textview));
text = gtk_entry_get_text (GTK_ENTRY (w->entry));
mark = gtk_text_buffer_get_insert (buffer);
gtk_text_buffer_get_iter_at_mark (buffer, &iter, mark);
gtk_text_buffer_insert (buffer, &iter, text, -1);
}
您可以使用以下命令编译此代码(假设文件名为file.c):
gcc file.c -o file `pkg-config --cflags --libs gtk+-2.0`
谢谢大家!
答案 0 :(得分:4)
也许您可以像插入其他字符一样插入换行符:
...
mark = gtk_text_buffer_get_insert (buffer);
gtk_text_buffer_get_iter_at_mark (buffer, &iter, mark);
/* Insert newline (only if there's already text in the buffer). */
if (gtk_text_buffer_get_char_count(buffer))
gtk_text_buffer_insert (buffer, &iter, "\n", 1);
gtk_text_buffer_insert (buffer, &iter, text, -1);
...
"\n"
是一个包含C中换行符的字符串,它在GTK中运行得很好(除非出于某些奇怪的原因在Windows中不存在)。
无益的模糊:1
可以很容易地-1
在这里;它只是告诉GTK它只需要读取1个字符,这可能会快一点。当然,这行代码几乎不应该成为瓶颈: - )