ComboBox in gtk2hs, glade

401 Views Asked by At

I have created Window, ComboBox, Buttons using glade and the code as following:

module Main where
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Glade

main = do
    initGUI
    Just xml <- xmlNew "Tp.glade"
    window <- xmlGetWidget xml castToWindow "window1"
    button <- xmlGetWidget xml castToButton "button1"

    comboBox  <- xmlGetWidget xml castToComboBox "combobox1"

    onClicked button $ do
         putStrLn $ "Apply button selected " 
         selected <- comboBoxGetActiveText comboBox

         print selected

   onDestroy window mainQuit
   widgetShowAll window
   mainGUI

If I select an option from the ComboBox and clicks the action button it shows the following error message UI.exe: user error (Pattern match failure in do expression at gtk\Graphics\UI\G tk\MenuComboToolbar\ComboBox.chs.pp:244:2-13)

Do I need to have separate Function for the action to be performed when I choose an option from the ComboBox? Please help me!!

2

There are 2 best solutions below

0
On

As stated in the Gtk2Hs docs, comboBoxGetActiveText "returns the currently active string in comboBox or Nothing if none is selected. Note that you can only use this function with combo boxes constructed with comboBoxNewText."

If you want to use this function, try one of the following options:

  • don't set the TreeModel of the combobox (probably a ListStore) in the Glade file and add the line comboBoxSetModelText comboBox after the line comboBox <- xmlGetWidget xml castToComboBox "combobox1". This might work right because comboBoxNewText "internally calls comboBoxSetModelText after creating a new combo box".
  • remove the combo box widget from the Glade file, create it yourself (replace the line comboBox <- xmlGetWidget xml castToComboBox "combobox1" with comboBox <- comboBoxNewText and pack it manually into the main window of your program.

Note that TreeModels can hold any type of data. Since Haskell works with data in a different way than imperative languages as C or Python, tree models created with Glade can't be imported into a Haskell application: you must define them inside your Haskell program.

0
On

If you use the comboBoxGetActive function, it will return an Int and you can then make a mapping to each element in the comboBox. This is found in the Graphics.UI.Gtk.MenuComboToolbar.ComboBox API.