所以,我有三个标签和一个输入框。我的目标是让您每次在输入框中输入内容并按回车键,文本都会出现在第三个标签中。如果您再次执行此操作,文本将出现在第三个标签中,而旧文本将移至第二个标签中,依此类推(因此标签显示您键入的最后三条消息。)
Here is the ChatInfo Struct:
typedef struct chat_info ChatInfo;
struct chat_info {
GtkWidget *text_line1;
GtkWidget *text_line2;
GtkWidget *text_line3;
GtkWidget *entry;
};
这是初始化聊天框的函数:
static void get_chatbox(GtkWidget ** vbox, gpointer data) {
GuiInfo *g = (GuiInfo *) data;
ChatInfo *c;
c = (ChatInfo *) malloc(sizeof(ChatInfo));
g->chat = c;
GtkWidget *text_line1;
GtkWidget *text_line2;
GtkWidget *text_line3;
GtkWidget *entry;
GtkEntryBuffer *buffer;
text_line1 = gtk_label_new("");
text_line2 = gtk_label_new("");
text_line3 = gtk_label_new("");
buffer = gtk_entry_buffer_new(NULL, -1);
entry = gtk_entry_new_with_buffer(buffer);
gtk_entry_set_activates_default(GTK_ENTRY(entry), TRUE);
gtk_box_pack_end(GTK_BOX(*vbox), entry, FALSE, FALSE, 1);
gtk_box_pack_end(GTK_BOX(*vbox), text_line3, FALSE, FALSE, 1);
gtk_box_pack_end(GTK_BOX(*vbox), text_line2, FALSE, FALSE, 1);
gtk_box_pack_end(GTK_BOX(*vbox), text_line1, FALSE, FALSE, 1);
gtk_misc_set_alignment((GtkMisc *) text_line1, .01, .5);
gtk_misc_set_alignment((GtkMisc *) text_line2, .01, .5);
gtk_misc_set_alignment((GtkMisc *) text_line3, .01, .5);
gtk_misc_set_alignment((GtkMisc *) entry, .01, .5);
g_signal_connect(G_OBJECT(entry), "activate", G_CALLBACK(send_message), g);
}
这是回调:
static void send_message(GtkWidget *window, gpointer data){
GuiInfo *g = (GuiInfo *) data;
ChatInfo *c = g->chat;
const gchar *message = gtk_entry_get_text(GTK_ENTRY(c->entry));
const gchar *oldtext3 = gtk_label_get_text(c->text_line3);
const gchar *oldtext2 = gtk_label_get_text(c->text_line2);
gtk_label_set_text(c->text_line3, message);
gtk_label_set_text(c->text_line2, oldtext3);
gtk_label_set_text(c->text_line1, oldtext2);
}
我在这条线上遇到了段错误,不知道为什么:
常量 gchar *message = gtk_entry_get_text(GTK_ENTRY(c->entry));