How does one find out if the mouse button is pressed on a label-like widget (or container?) in gtk2hs?

StackOverflow https://stackoverflow.com/questions/5127009

سؤال

Below is a simple example using gtk2hs that adds a label and then a click handler on it. The buttonPressEvent handler is never called when you click on the label. The button could be put in a container, but... do containers fire the button pressed signal?

I have a rectangular area that has some text in it (currently using label) that I need to know if the user clicked in it. I don't want it to look like a button.

{-# LANGUAGE PackageImports #-}

import Graphics.UI.Gtk
import Graphics.UI.Gtk.Gdk.EventM
import Graphics.UI.Gtk.Gdk.GC
import "mtl" Control.Monad.Trans(liftIO)

main = do
  initGUI
  window <- windowNew
  window `onDestroy` mainQuit

  label0 <- labelNew $ Just "static label"
  widgetAddEvents label0 [ButtonPressMask] -- is this necessary? Still doesn't work with it, though
  label0 `on` buttonPressEvent $ tryEvent $ do
    liftIO $ putStrLn "static label clicked"
  containerAdd window label0

  widgetShowAll window
  mainGUI
هل كانت مفيدة؟

المحلول

You want to use an event-box for that. It's a container that captures events.

Here's a version that works.

{-# LANGUAGE PackageImports #-}

import Graphics.UI.Gtk
import Graphics.UI.Gtk.Gdk.EventM
import Graphics.UI.Gtk.Gdk.GC
import "mtl" Control.Monad.Trans(liftIO)

main = do
  initGUI
  window <- windowNew
  window `onDestroy` mainQuit

  label0 <- labelNew $ Just "static label"

  eventBox0 <- eventBoxNew
  eventBox0 `on` buttonPressEvent $ tryEvent $ do
    liftIO $ putStrLn "static label clicked"

  containerAdd eventBox0 label0
  containerAdd window eventBox0

  widgetShowAll window
  mainGUI

نصائح أخرى

The GTK docs say that there's no such signal as a button press emitted by labels.

Rightly so, I'd say, you're supposed to use buttons for such things. Admittedly, though, gtk2hs could be more strictly typed and catch that.

Alternatively, you can add links to your label text and then override the appropriate signals.

Make the label selectable:

set label0 [labelSelectable := True]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top