riconshandlergwidgets

toggling a group of icons in gWidgets


Adapting an example I can toggle the display of an icon like this:

reject <- "D:/Pictures/web/close32.png"
accept <- "D:/Pictures/web/open32.png"
w= gwindow()
g1 <- ggroup(horizontal=TRUE, cont=w)
icon <- gimage(reject,cont=g1)
state <- FALSE # a global
changeState <- function(h,...) {
   if(state) {
     svalue(icon) <- reject
     } else {
       svalue(icon) <- accept
       }
   state <<- !state
}
addHandlerClicked(icon, handler=changeState)

However, I would like to get this to work with a group of icons example 3x3 icon grouping http://cran.r-project.org/web/packages/gWidgets/vignettes/gWidgets.pdf so that each icon can be toggled and I can retrieve the state of the icons as a vector. The purpose is to create a graphical selector for picking pairs of observations to perform analysis on. Here is my attempt. It displays correctly, but does not respond to clicks to change the state. I recognize that I am confusing how the handler and action parameters act together and would appreciate any clarifications and fixes for this code.

reject <- "D:/Pictures/web/close32.png"
accept <- "D:/Pictures/web/open32.png"
w= gwindow()
g1 <- ggroup(horizontal=TRUE, cont=w)
lyt <- glayout(cont=g1, spacing=10)
icon <- rep(reject,times=9)
state <- rep(FALSE, times=9)

changeState <- function(h,...) {
  if(state[index]) {
    svalue(icon[index]) <- reject
  } else {
    svalue(icon[index]) <- accept
  }
  state[index] <<- !state[index]
}

for(i in 1:3){
  for(j in 1:3){
    ind <- (i-1) * 3 +j
    lyt[i,j] <- gimage(icon[ind], cont=lyt)
    addHandlerClicked(lyt[i,j], handler=changeState, action= index <-ind)
  }  
}

1c: https://i.sstatic.net/4kbwK.png


Solution

  • The index value must be retrieved from h$action in your handler (index <- h$action). As well, this bit action=index <- ind need only be action=ind.