为什么按钮不在gtk2hs的表格中呈现

时间:2018-03-08 20:04:49

标签: haskell gtk2hs

我正在尝试在gtk2hs中编写一个简单的UI。它以两个文本框和一个按钮开头。当按下按钮时,它会生成一个大小为(m,n)的按钮表,其中m和n取自文本框。出于某种原因,当按下按钮时,会为表分配空间,但不会显示任何按钮!

import Graphics.UI.Gtk
import Control.Concurrent

t2l :: Int -> Int -> Int -> Int -> Int 
t2l r c rr cc = (r * cc) + c 

buildTable :: Int -> Int -> IO(Table, [Button])
buildTable r c = do
   t <- tableNew r c True
   buttons <- sequence $ take (r * c) (repeat buttonNew)
   mapM (`set` [buttonLabel := "HELLO"]) buttons
   return [tableAttachDefaults t (buttons !! (t2l rr cc r c)) cc (cc+1) rr (rr+1) | cc <- [0..(c+1)] , rr <- [0..(r+1)]]
   return (t,buttons)

main = do
   initGUI
   window <- windowNew
   mainSplit <- vBoxNew False 10
   contPannel <- hBoxNew False 5

   rowTF <- entryNew
   colTF <- entryNew
   buildBTN <- buttonNew
   set buildBTN [buttonLabel := "Build Table"]

   set window [containerChild := mainSplit]
   boxPackStart mainSplit contPannel PackGrow 0
   boxPackStart contPannel rowTF PackGrow 0
   boxPackStart contPannel colTF PackGrow 0
   boxPackStart contPannel buildBTN PackNatural 0

   on window objectDestroy mainQuit
   widgetShowAll window

   on buildBTN buttonActivated $ do
      rT <- get rowTF entryText
      cT <- get colTF entryText
      r <- return $ read rT
      c <- return $ read cT
      (t,b) <- buildTable r c 
      boxPackStart mainSplit t PackGrow 0
      widgetShowAll t
      return ()

   mainGUI

1 个答案:

答案 0 :(得分:0)

我不是100%确定错误产生的原因,我有一些新的代码可以运行:

import Graphics.UI.Gtk
import Control.Concurrent

mkBtn :: String -> IO Button
mkBtn label = buttonNew >>= (\b -> set b [buttonLabel := label] >> return b)

buildTable :: Int -> Int -> IO(Grid)
buildTable r c = do
   t <- gridNew
   gridSetRowHomogeneous t True
   mapM (\f -> mkBtn "Hello" >>= (\b -> gridAttach t b (f `mod` c) (f `div` c) 1 1)) [0..(r*c)-1]
   return (t) 

main = do
   initGUI
   window <- windowNew
   mainSplit <- vBoxNew False 10
   contPannel <- hBoxNew False 5

   rowTF <- entryNew
   colTF <- entryNew
   buildBTN <- buttonNew
   set buildBTN [buttonLabel := "Build Table"]

   set window [containerChild := mainSplit]
   boxPackStart mainSplit contPannel PackGrow 0
   boxPackStart contPannel rowTF PackGrow 0
   boxPackStart contPannel colTF PackGrow 0
   boxPackStart contPannel buildBTN PackNatural 0

   on window objectDestroy mainQuit
   widgetShowAll window

   on buildBTN buttonActivated $ do
      rT <- get rowTF entryText
      cT <- get colTF entryText
      r <- return $ read rT
      c <- return $ read cT
      t <- buildTable r c 
      boxPackStart mainSplit t PackGrow 0
      widgetShowAll t
      return ()

   mainGUI

也许有人会知道为什么会这样,最后却没有?我假设这是我创建新按钮的方式。

我改变的第一件事是从gtk2到3,这使我能够使用网格而不是表格。我没有使用重复,而是使用了辅助函数mkBtn。其他变化就是我如何填充网格。我使用mapM而不是一个相当愚蠢的列表理解,并将按钮列表中的索引转换为表格坐标而不是表格坐标列表索引(最初在t2l中完成)