098. How to create a simple drag and drop image viewer?

Problem

You want to create a simple image viewer that allows users to drag a gif/jpg/png image file from a file explorer and drop it into the image viewer as shown below:

How to create a simple drag and drop image viewer?


Solution


Sample Code

1   
2   
3   
4   
8   
9   
12   
13   
16   
22   
23   
24   
25   
26   
28   
29   
30   
31   
32   
35   
37   
39   
40   
43   
44   
45   
46   
<?php
$window = new GtkWindow();
$window->set_size_request(400, 300);
$window->connect_simple('destroy', array('Gtk','main_quit'));

$img = new GtkImage();
$img->drag_dest_set(Gtk::DEST_DEFAULT_ALL, 
    array( array( 'text/uri-list', 0, 0)), Gdk::ACTION_COPY); // note 1
$img->connect('drag-data-received', 'on_drop', $img); // note 1

$scrolled_win = new GtkScrolledWindow(); // note 2
$scrolled_win->set_policy( Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
$window->add($scrolled_win);
$scrolled_win->add_with_viewport($img); // note 3
$window->show_all();
Gtk::main();

// process drop
function on_drop($widget, $context, $x, $y, $data, $info, $time, $img) {
    $uri_list = explode("\n",$data->data);
    $img_file = $uri_list[0];
    $img_file = str_replace("file:///", "", $img_file);
    $img_file = str_replace("\r", "", $img_file);
    $img->set_from_file($img_file); // note 4
}

?>

Output

As shown above.
 

Explanation

  1. Set up the GtkImage so that it allows users to drop an image onto it.
  2. Create a scroll window.
  3. Stuff the img in the scroll window. Note the use of GtkScrolledwindow::add_with_viewport().
  4. Display the image using the filename "dropped" onto the image viwer.

Related Links

Add comment


Security code
Refresh