0

我的盒子运行 Ubuntu 21.10。我使用 GTK4、C 语言和 XML 描述 GUI。我一般是 GUI 新手,尤其是 GTK4。

该程序使用 GtkFileChooserWidget 因为我需要一个 Widget,它除了嵌入到主窗口之外,还根据用户的导航在其右窗格中显示文件和文件夹列表。

该程序的目标只是捕获用户刚刚在 GtkFileChooserWidget 右侧窗格的文件和文件夹列表中单击的文件夹名称(仅文件夹名称,而不是文件名称)。

代码(见下文)有两个问题:

  1. 捕获的文件夹的名称不是刚刚执行的单击的名称,而是上一次单击的名称;
  2. 在单击 GtkFileChooserWidget 上部显示的“完整路径”后,该程序还会捕获文件夹的名称,该程序不应授权。

这是 XML 代码:

<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <requires lib="gtk" version="4.0"/>
  <object class="GtkWindow" id="window1">
    <property name="child">
      <object class="GtkGrid" id="grid1">
        <child>
          <object class="GtkFrame" id="frame1">
            <child>
              <object class="GtkFileChooserWidget" id="folderChooserWidget1">
                <property name="action">select-folder</property>
                <property name="select-multiple">True</property>
              </object>
            </child>
          </object>
        </child>
      </object>
    </property>
  </object>
</interface>

这是C代码:

#include <gtk/gtk.h>
#include <glib/gprintf.h>

static void on_click (GtkGestureClick *controller, int n, double x, double y, GtkFileChooser *folderChooser)
{
  GFile *file = NULL;
  char *basename = (char *)NULL;

  file  = gtk_file_chooser_get_file (folderChooser);
  if (file == NULL)
    g_printf ("No folder selected!\n");
  else
  {
    basename = g_file_get_basename (file);
    g_printf ("folder selected: %s\n", basename);
    g_free (basename);
  }
}    

static void app_activate (GApplication *application)
{
  GtkApplication *app;
  GtkBuilder *builder1;
  GObject *window1;
  GObject *folderChooserWidget1;

  app = GTK_APPLICATION (application);

  builder1 = gtk_builder_new ();
  gtk_builder_add_from_file (builder1, "xml.ui", NULL);

  window1 = gtk_builder_get_object (builder1, "window1");
  gtk_window_set_application (GTK_WINDOW (window1), app);

  folderChooserWidget1 = gtk_builder_get_object (builder1, "folderChooserWidget1");
  GtkGesture *controller;
  controller = gtk_gesture_click_new ();
  gtk_gesture_single_set_button (GTK_GESTURE_SINGLE (controller), 0);
  gtk_gesture_single_set_exclusive (GTK_GESTURE_SINGLE (controller), TRUE);
  gtk_event_controller_set_propagation_phase (GTK_EVENT_CONTROLLER (controller), GTK_PHASE_CAPTURE);
  g_signal_connect_after (controller, "pressed", G_CALLBACK (on_click), GTK_FILE_CHOOSER (folderChooserWidget1));
  gtk_widget_add_controller (GTK_WIDGET (folderChooserWidget1), GTK_EVENT_CONTROLLER (controller));


  gtk_widget_show (GTK_WIDGET (window1));

  g_object_unref (builder1);
}    

int main (int argc, char *argv[])
{
  GtkApplication *app;
  int status;

  app = gtk_application_new ("xx.yy.zz", G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (app_activate), NULL);
  status = g_application_run (G_APPLICATION (app), argc, argv);

  g_object_unref (app);

  return (status);
}
4

0 回答 0