如何在 GTK3 中进行拖放操作 [英] How do I do drag and drop in GTK3

查看:68
本文介绍了如何在 GTK3 中进行拖放操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 GTK3 中拖放.代码 这里 适用于 GTK2,不适用于GTK3.编译器抱怨 onDragDataReceived 中的 seldata 中没有 data 元素.而且,如果您在一次拖放中有多个文件,这将不起作用.

I was wondering how to drag and drop in GTK3. The code here is for GTK2, and does not work in GTK3. The compiler complains about there being no data element in seldata in onDragDataReceived. And also, this would not work if you have multiple files in one drag and drop.

推荐答案

如何在 GTK3 中进行拖放操作

How to do drag and drop in GTK3

此处实现的拖放仅用于将文件复制到应用程序中.所以,首先要做的是做你的目标条目,这就是可以拖入的东西.对于文本编辑器,你会允许文本被拖入.但在这个例子中,我们只想拖入文件.

The drag and drop implemented here is only for copying files into an application. So, the first thing to do is to make your target entries, that is what sort of thing can be dragged in. For text editors, you would allow text to be dragged in. But in this example, we only want to drag in files.

static GtkTargetEntry targetentries[] =
{
    { "text/uri-list", 0, 0}
};

现在我们有了目标条目,我们可以将特定的小部件变成拖放目的地.

Now that we have the target entries, we can make the specific widget into a drag and drop destination.

gtk_drag_dest_set ( your_widget_here, GTK_DEST_DEFAULT_ALL, targetentries, 1, GDK_ACTION_COPY);

现在是信号处理程序:

g_signal_connect (your_widget_here, "drag-data-received", G_CALLBACK (on_drag_data_received), some_data_to_pass_along);

因此,当您将文件放在小部件上时,它会发出信号,因为您已将其设置为 dnd 目的地.

So, when you drop a file on your widget, it will emit the signal, because you prep’d it by making it a dnd destination.

这里是回调函数:

void on_drag_data_received (GtkWidget *wgt, GdkDragContext *context, gint x, gint y, GtkSelectionData *seldata, guint info, guint time, gpointer data)
{
    gchar **filenames = NULL;
    filenames = g_uri_list_extract_uris((const gchar *) gtk_selection_data_get_data (seldata));
    if (filenames == NULL) // If unable to retrieve filenames:
    {
        g_printerr("FAILURE!");
        gtk_drag_finish(context, FALSE, FALSE, time); // Drag and drop was a failure.
        return;
    }
    int iter = 0;
    while(filenames[iter] != NULL) // The last URI list element is NULL.
    {
        char *filename = g_filename_from_uri (filenames[iter], NULL, NULL); 
        // Do something useful with the file, like opening it, right here.
        iter++;
    }
    gtk_drag_finish(context, TRUE, FALSE, time); // Drag and drop was successful!
}

大功告成!

这篇关于如何在 GTK3 中进行拖放操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆