Search code examples
rcheckboxgwidgets

gWidgetRGtk2 gcheckbox list addition/subtraction with looping


I've been trying to get his to work all day, but I can't find a simple explanation on how this works. I have a vector with 3 items, c(file1, file2, file3), I want to be able to toggle the checkbox on and off, when its on I want the first item c(file1) to be in the vector, however when its off I want it to be deleted from the vector. This is my attempt at it, but I don't know why its not working:

library(gWidgetRGtk2)
GraphFiles <- FileNamesOrig

w <- gwindow("Tag Density Checkboxes")
g <- ggroup(container = w)
lyt <- glayout(cont = g, horizontal = T)

gcheckbox(FileNamesOrig[1], container=g, checked=TRUE, handler=function(h,...){  
  if(!svalue(h$obj)){GraphFiles[[1]] <- NA}  else {GraphFiles[[1]] <-FileNamesOrig[1]}
})

While we're all here, I was thinking of doing:

for(i in 1:No.file)
gcheckbox(GraphFiles[i], container=g, handler=function(h,...){
  })

No.file = 3

First, how would I get the check-boxes on a separate line within the GUI window. And second how would I incorporate the functionality of the first piece of code into the loop? (the problem is the number of input will differ each run of the script)


Solution

  • You can use [, see ?ggwidget

    The "[" method returns the label on the box.

    then I change your handler function:

     handler=function(h,...){  
             browser()
             label <- h$obj[]
             if(!svalue(h$obj)) ## I remove the item
                GraphFiles <<- GraphFiles[GraphFiles!=label]   ## note the use of the global 
                                                                  operator
             else               ## I add the item
                GraphFiles  <<- c(GraphFiles,FileNamesOrig[FileNamesOrig==label])
    
     })
    

    finally you call this in loop:

    library(gWidgetsRGtk2)
    FileNamesOrig <- paste('file',1:3,sep='')
    GraphFiles <- FileNamesOrig
    w <- gwindow("Tag Density Checkboxes")
    g <- ggroup(container = w)
    lyt <- glayout(cont = g, horizontal = T)
    for(x in seq_along(FileNamesOrig)){
      gcheckbox(FileNamesOrig[x], 
                container=g, 
                checked=TRUE, 
                handler=function(h,...){  
                      label <- h$obj[]
                      if(!svalue(h$obj)) GraphFiles <<- GraphFiles[GraphFiles!=label]
                      else GraphFiles  <<- c(GraphFiles,FileNamesOrig[FileNamesOrig==label])
                     print(GraphFiles) ## edit to show the changes
                })
    }