GTK + 3.0 C ++将GtkTextBuffer传递给函数

时间:2014-11-02 18:23:32

标签: c++ gtk gtk3 glib

当我尝试将文件从文件加载到TextView时,我正在学习GTK +库并遇到一些问题。

// 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);

当我尝试在main.cpp中更改textBuffer时,一切顺利。但...

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);
}

从文件加载每一行后,GTK将运行时错误输出到控制台:

(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

我试过这样做:

GTK_TEXT_BUFFER(buffer)

但它只是给了我另一个错误

(asdddd.exe:3872): GLib-GObject-WARNING **: invalid cast from `GtkMenuItem' to `
GtkTextBuffer'

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

GtkMenuItem :: activate的签名是

void signalHandler(GtkMenuItem *sender, gpointer user_data);

您的信号处理程序(在本例中为showOpenFileDialog())必须具有此签名。在您的情况下,您正确地将文本缓冲区传递到g_signal_connect()行,但是会将其分配给user_data参数(GtkMenuItem本身,在本例中为{{1} },是openFile)。

不幸的是,GObject信号无法进行静态类型检查。我不知道是否存在可以提供帮助的静态分析工具。

答案 1 :(得分:0)

您需要使用void showOpenFileDialog(GtkMenuItem *openFile, GtkTextBuffer *buffer)作为回调,因为第一个参数将是调用者,第二个参数是user_data作为最后一个参数传递给g_signal_connect