
Hi! I tried to implement a simple counter with gtk2hs. To increase my counter I defined following event: onClicked btn $ do si <- textBufferGetStartIter tb ei <- textBufferGetEndIter tb val <- textBufferGetText tb si ei False textBufferSetText tb $ show $ (+1) $ read val But now I don't want always read the textfield to get my counter-value, I would like to save the state of my increased value and would like to pass it to the next call of the function. How can I do this? thanks Christian This is the complete code: import Gtk quitDialog :: IO Bool quitDialog = ..... main :: IO () main = do initGUI --main window win <- windowNew onDelete win (\_->(quitDialog>>= (return . not ))) onDestroy win mainQuit vb <- vBoxNew True 5 hb <- hBoxNew True 5 btn <- buttonNewFromStock stockExecute btn2 <- buttonNewFromStock stockQuit tv <- textViewNew tb <- textBufferNew Nothing textBufferSetText tb "0" textViewSetEditable tv False textViewSetCursorVisible tv False textViewSetBuffer tv tb boxPackStartDefaults vb tv boxPackStartDefaults vb hb boxPackStartDefaults hb btn boxPackStartDefaults hb btn2 hgf <- onClicked btn $ do si <- textBufferGetStartIter tb ei <- textBufferGetEndIter tb val <- textBufferGetText tb si ei False textBufferSetText tb $ show $ (+1) $ read val disconnect hgf onClicked btn2 $ do quit <- quitDialog if quit then widgetDestroy win else return () containerAdd win vb widgetShowAll win mainGUI

On Fri, 13 Jun 2003 19:39:53 +0200
Christian Buschmann
I tried to implement a simple counter with gtk2hs. To increase my counter I defined following event:
onClicked btn $ do si <- textBufferGetStartIter tb ei <- textBufferGetEndIter tb val <- textBufferGetText tb si ei False textBufferSetText tb $ show $ (+1) $ read val
But now I don't want always read the textfield to get my counter-value, I would like to save the state of my increased value and would like to pass it to the next call of the function. How can I do this?
Use an IORef or an MVar eg. (untested code) let initialCounterValue = 0 counter <- newIORef initialCounterValue btn `onClicked` do counterValue <- readIORef counter tb `textBufferSetText` show (counterValue + 1) writeIORef counter (counterValue + 1) or with an MVar: let initialCounterValue = 0 counter <- newMVar initialCounterValue btn `onClicked` do modifyMVar_ counter (\counter -> do tb `textBufferSetText` show (counterValue + 1) return (counterValue + 1)) The second version is threadsafe. There are more elegant techniques that hide the evil imperitive state (the IORef or MVar) but this is the easiest technique to start with. Duncan
participants (2)
-
Christian Buschmann
-
Duncan Coutts