Reputation: 134
I'm learning the GTK+ library and got some problem, when I try to load text from file to TextView.
// main.cpp
GtkWidget *textInput;
GtkTextBuffer *textBuffer;
[...]
//Create text input field
textInput = gtk_text_view_new();
gtk_box_pack_start(GTK_BOX (vbox), textInput, 1, 1, 0);
textBuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW (textInput));
// Menu actions
g_signal_connect(G_OBJECT(openFile), "activate", G_CALLBACK(showOpenFileDialog), textBuffer);
When I try to change textBuffer in main.cpp, all goes well. But...
void showOpenFileDialog(GtkTextBuffer *buffer)
{
GtkWidget *openFileDialog;
openFileDialog = gtk_file_chooser_dialog_new("Open file", GTK_WINDOW(NULL), GTK_FILE_CHOOSER_ACTION_OPEN,GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL);
gtk_dialog_run(GTK_DIALOG(openFileDialog));
const gchar *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(openFileDialog));
ifstream file(filename);
string line;
if(file.is_open())
{
while(getline(file, line))
{
GtkTextIter endOfTextInput;
gtk_text_buffer_get_end_iter(buffer, &endOfTextInput);
gtk_text_buffer_insert(buffer, &endOfTextInput, line.c_str(), line.size());
}
}
gtk_widget_destroy(openFileDialog);
}
With every line loaded from file, GTK outputs runtime errors to console:
(asdddd.exe:3872): Gtk-CRITICAL **: gtk_text_buffer_get_end_iter: assertion `GTK
_IS_TEXT_BUFFER (buffer)' failed
(asdddd.exe:3872): Gtk-CRITICAL **: gtk_text_buffer_insert: assertion `GTK_IS_TE
XT_BUFFER (buffer)' failed
I tried doing this:
GTK_TEXT_BUFFER(buffer)
But it just given me another error
(asdddd.exe:3872): GLib-GObject-WARNING **: invalid cast from `GtkMenuItem' to `
GtkTextBuffer'
Can anyone help me?
Upvotes: 0
Views: 549
Reputation: 11578
The signature for GtkMenuItem::activate is
void signalHandler(GtkMenuItem *sender, gpointer user_data);
Your signal handler (in this case, showOpenFileDialog()
) must have this signature. In your case, you're passing the text buffer into the g_signal_connect()
line properly, but that gets assigned to the user_data
argument (the GtkMenuItem
itself, in this case openFile
, is the sender
).
It is unfortunate that there cannot be static type checking for GObject signals. I do not know if a static analysis tool exists that can help.
Upvotes: 1
Reputation: 6886
You need to use void showOpenFileDialog(GtkMenuItem *openFile, GtkTextBuffer *buffer)
for the callback, since the first argument will be the caller, the second one the user_data
you pass to g_signal_connect
as last argument.
Upvotes: 0