How to return values from gWidgets and handlers?

后端 未结 3 596
半阙折子戏
半阙折子戏 2021-02-04 15:52

I am trying to develop a GUI (using gWidgets) for an R package. My plan was to construct a main window holding the data, and with buttons calling small gui wrappers for each fun

3条回答
  •  粉色の甜心
    2021-02-04 16:40

    A better approach, but one that involves a bigger reworking of your code, is to store GUIs in reference classes.

    You call setRefClass with a list of fields (one for each widget), and define an initialise method where the GUI is created. I usually create a function to wrap the call that creates an instance. See setRefClass at the end of the code block.

    mainGui <- suppressWarnings(setRefClass( #Warnings about local assignment not relevant 
      "mainGui",
      fields = list(
        #widgets
        w   = "ANY",       #"GWindow"
        txt = "ANY",       #"GEdit"
        btn = "ANY"        #"GButton"
      ),
      methods = list(
        initialize = function(windowPosition = c(0, 0))
        {
          "Creates the GUI"
    
          w <<- gwindow(
            "Main window", 
            visible = FALSE,
            parent  = windowPosition
          )
    
          txt <<- gedit(
            "Initial text in main window.", 
            container = w
          )      
    
          btn <<- gbutton(
            "Send to sub window", 
            container = w
          )      
    
          addHandlerChanged(
            btn, 
            handler = function(h, ...) {
              subWindow$setText(getText())
            } 
          )
    
          visible(w) <- TRUE      
        },
        #other methods to access GUI functionality go here
        getText = function() 
        {
          svalue(txt)
        },
        setText = function(newTxt) 
        {
          svalue(txt) <- newTxt
        }
      )
    ))  
    
    createMainGui <- function(...)
    {
      invisible(mainGui$new(...))
    }    
    

提交回复
热议问题