Пример #1
0
    def loadSettings(self,data):
        # print _('loadSettings for a filter table')
        # print data
        if not data: return
        if 'Rdata' not in data:
            if data['modelSettings'] == None: 
                print 'modelsettings not found'
                return
            
            print 'loading with 1.90 settings'
            print data['modelSettings']
            if 'class' not in data:
                redRLog.log(redRLog.REDRCORE, redRLog.WARNING, 'the class attribute is not found in the data %s' % str(data))
                return
            #import imp, redRObjects
            #fp, pathname, description = imp.find_module('libraries', [redREnviron.directoryNames['redRDir']])
            #varc = imp.load_module('libraries', fp, pathname, description)
            
            #for mod in data['class'].replace("<'", '').replace("'>", '').split('.')[1:]:
            #    varc = getattr(varc, mod)
            # Get the widget and instantiate a data table signal that will then generate the table model for us.
            #self.tm = varc(redRObjects.getWidgetInstanceByID(data['modelSettings']['parentWidget']), **data['modelSettings'])
            import redRObjects
            signal = redRObjects.signalFromSettings(data['signal'])
            self.tm = signal.getTableModel(self, self.filterable, self.sortable)
            #self.setTable(var, filterable = self.filterable, sortable = self.sortable) 
            
            self.setModel(self.tm)
            self.dataInfo.setText(self.tm.getSummary())
            selModel = self.selectionModel()
            # print selModel
            
            if 'selection2' in data.keys() and len(data['selection2']):
                for x in data['selection2']:
                    selModel.select( QItemSelection(self.tm.createIndex(x[0],x[1]),self.tm.createIndex(x[2],x[3])),QItemSelectionModel.Select)
                    
        elif data['Rdata'] == None:
            self.clear()
        else:
            redRLog.log(redRLog.REDRCORE, redRLog.WARNING, 'DEPRICATION WARNING. Filter table loading of 1.85 settings will not be available in 2.0.  Please resave your old files using these settings before upgrading to 2.0')
            from libraries.base.signalClasses.RDataFrame import RDataFrameModel
            self.tm = RDataFrameModel(parent = self, Rdata = data['Rdata'], filterable=self.filterable, sortable=self.sortable)
            self.setModel(self.tm)
            self.dataInfo.setText(self.tm.getSummary())
            
            #self.Rdata = data['Rdata']
            #self.criteriaList = data['criteriaList']
            ## print 'filtering data on the following criteria %s' % unicode(self.criteriaList)
            #self.filter()

            #if 'sortIndex' in data.keys():
                #self.sortByColumn(data['sortIndex'][0],data['sortIndex'][1])
            selModel = self.selectionModel()
            ## print selModel
            
            if 'selection2' in data.keys() and len(data['selection2']):
                for x in data['selection2']:
                    selModel.select( QItemSelection(self.tm.createIndex(x[0],x[1]),self.tm.createIndex(x[2],x[3])),QItemSelectionModel.Select)
            
            
            if 'selection' in data.keys() and selection and len(data['selection']):
                progressBar = self.startProgressBar(_('Filter Table Loading'), _('Loading Fiter Table'), 50)

                if len(data['selection']) > 1000:
                    mb = QMessageBox.question(None, _('Setting Selection'), _('There are more than 1000 selections to set for %s,\ndo you want to discard them?\nSetting may take a very long time.') % self.label, QMessageBox.Yes, QMessageBox.No)
                    if mb.exec_() == QMessageBox.No:
                    
                        progressBar.setLabelText(_('Loading Selections'))
                        progressBar.setMaximum(len(data['selection']))
                        progressBar.setValue(0)
                        val = 0
                        for i in data['selection']:
                            selModel.select(self.tm.createIndex(i[0],i[1]),QItemSelectionModel.Select)
                            val += 1
                            progressBar.setValue(val)
                progressBar.hide()
                progressBar.close()
Пример #2
0
 def setStructuredDictTable(self, data):
     self.tm = StructuredDictTableModel(data, self, [], False, False, True)
     self.setModel(self.tm)
     self.dataInfo.setText(self.tm.getSummary())
Пример #3
0
 def clear(self):
     self.tm = BlankTable()
     self.setModel(self.tm)
     #self.setRTable('matrix("")')
     self.criteriaList = {}
Пример #4
0
class filterTable(widgetState, QTableView):
    def __init__(self,widget,label=None, displayLabel=True, Rdata=None, 
    editable=False, sortable=True, filterable=False,
    selectionBehavior=QAbstractItemView.SelectRows, 
    selectionMode = QAbstractItemView.ExtendedSelection, 
    showResizeButtons = True,
    onFilterCallback = None,
    callback=None,
    selectionCallback=None,**kwargs):
        kwargs.setdefault('includeInReports', True)
        kwargs.setdefault('sizePolicy', QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred))
        widgetState.__init__(self,widget,label,**kwargs)
        
        if displayLabel:
            mainBox = groupBox(self.controlArea,label=label, orientation='vertical')
        else:
            mainBox = widgetBox(self.controlArea,orientation='vertical')
        self.label = label
        
        QTableView.__init__(self,self.controlArea)
        mainBox.layout().addWidget(self)
        box = widgetBox(mainBox,orientation='horizontal')
        leftBox = widgetBox(box,orientation='horizontal')
        if filterable:
            self.clearButton = button(leftBox,label=_('Clear All Filtering'), callback=self.clearFiltering)
        self.dataInfo = widgetLabel(leftBox,label='',wordWrap=False) 
        box.layout().setAlignment(leftBox, Qt.AlignLeft)

        
        if showResizeButtons:
            resizeColsBox = widgetBox(box, orientation="horizontal")
            resizeColsBox.layout().setAlignment(Qt.AlignRight)
            box.layout().setAlignment(resizeColsBox, Qt.AlignRight)
            widgetLabel(resizeColsBox, label = _("Resize columns: "))
            button(resizeColsBox, label = "+", callback=self.increaseColWidth, 
            toolTip = _("Increase the width of the columns"), width=30)
            button(resizeColsBox, label = "-", callback=self.decreaseColWidth, 
            toolTip = _("Decrease the width of the columns"), width=30)
            button(resizeColsBox, label = _("Resize To Content"), callback=self.resizeColumnsToContents, 
            toolTip = _("Set width based on content size"))

        
        self.R = Rcommand
        self.Rdata = None
        self.filteredData = None
        self.sortIndex = None
        self.criteriaList = {}
        self.parent = widget
        self.tm=None
        self.sortable=sortable
        self.editable=editable
        self.filterable=filterable
        self.onFilterCallback = onFilterCallback
        self.selectionCallback = selectionCallback
        # self.selections = QItemSelection()
        self.working = False

        self.setHorizontalHeader(myHeaderView(self))
        self.setSelectionBehavior(selectionBehavior)
        self.setAlternatingRowColors(True)
        
        # self.horizontalHeader().setMovable(True)
        
        if selectionMode != -1:
            self.setSelectionMode(selectionMode)
    
        if Rdata:
            self.setRTable(Rdata)

        if editable:
            self.horizontalHeader().hide()
            self.verticalHeader().hide()
            
        if sortable:
            self.horizontalHeader().setSortIndicatorShown(True)
            self.horizontalHeader().setSortIndicator(-1,0)
        if filterable or sortable:
            self.horizontalHeader().setClickable(True)
            self.horizontalHeader().setContextMenuPolicy(Qt.CustomContextMenu)
            self.horizontalHeader().customContextMenuRequested.connect(self.headerClicked)

            
        if callback:
            QObject.connect(self, SIGNAL('clicked (QModelIndex)'), callback)
    def selectColumn(self,val):
        print 'selectColumn#############################', val

    def cellSelection(self,newSelected,oldSelected):
        
        selections = self.selectionModel().selection()
        if self.working:
            return 
        self.working = True
        self.selectionCallback(selections)
        self.working = False
    def setDataModel(self, data, filtered = False):
        self.tm = data.getTableModel(self, filtered)
        self.setModel(self.tm)
        self.dataInfo.setText(self.tm.getSummary())
        
    def setTable(self, data, filterable = None, sortable = None):
        """Sets the table to a table model returned from a signal.  data represents a Red-R signal that contains a table model function getTableModel()."""
        if not 'getTableModel' in [method for method in dir(data) if callable(getattr(data, method))]: 
            # check if the data has a getTableModel method, if not then we should kill the processing and place a blank table in the object's place.
            self.clear()
            return
            
        if filterable != None:
            self.filterable = filterable
        if sortable != None:
            self.sortable = sortable
        
        self.tm = data.getTableModel(self, self.filterable, self.sortable)
        print self.tm, "Table model"
        self.setModel(self.tm)
        self.dataInfo.setText(self.tm.getSummary())
        
    def setStructuredDictTable(self, data):
        self.tm = StructuredDictTableModel(data, self, [], False, False, True)
        self.setModel(self.tm)
        self.dataInfo.setText(self.tm.getSummary())
    
    def setRTable(self,data, setRowHeaders = 1, setColHeaders = 1,filtered=False):
        """Conveinience function for setting an R table.  Data should be a tuple of (parentWidget, Rdata)"""
        #redRLog.log(redRLog.REDRCORE, redRLog.WARNING, 'setRTable method depricated, use setTable instead.')
        self.tm = signals.base.RDataFrame(data[0], data = data[1]).getTableModel(self)
        self.setModel(self.tm)
    
    def setModel(self, model):
        QTableView.setModel(self, model)
        if self.selectionCallback:
            self.connect(self.selectionModel(),  
                         SIGNAL("selectionChanged(QItemSelection, QItemSelection)"),  
                         self.cellSelection) 

    def resizeColumnsToContents(self):
        QTableView.resizeColumnsToContents(self)
        for i in range(self.tm.columnCount(self)):
            if self.columnWidth(i) > 600:
                self.setColumnWidth(i,600)

    def increaseColWidth(self):        
        for col in range(self.tm.columnCount(self)):
            w = self.columnWidth(col)
            self.setColumnWidth(col, w + 10)

    def decreaseColWidth(self):
        for col in range(self.tm.columnCount(self)):
            w = self.columnWidth(col)
            minW = self.sizeHintForColumn(col)
            self.setColumnWidth(col, max(w - 10, minW))

    def columnCount(self):
        if self.tm:
            return self.tm.columnCount(self)
        else:
            return 0
    
    def rowCount(self):
        if self.tm:
            return self.tm.rowCount(self)
        else:
            return 0
    
    def copy(self):
        """Copies data to the clipboard"""
        selection = self.selectionModel() #self.table = QAbstractItemView
        indexes = selection.selectedIndexes()

        columns = indexes[-1].column() - indexes[0].column() + 1
        rows = len(indexes) / columns
        textTable = [[""] * columns for i in xrange(rows)]

        for i, index in enumerate(indexes):
         textTable[i % rows][i / rows] = unicode(self.tm.data(index,Qt.DisplayRole).toString()) #self.model = QAbstractItemModel 

         qApp.clipboard().setText("\n".join(("\t".join(i) for i in textTable)))
    
    def keyPressEvent(self, event):
        if event.matches(QKeySequence.Copy):
            self.copy()
        else:
            QTableView.keyPressEvent(self,event)

    def addRows(self,count,headers=None):
        self.tm.insertRows(self.tm.rowCount(self),count,headers=headers)
    def addColumns(self,count,headers=None):
        self.tm.insertColumns(self.tm.columnCount(self),count,headers)
    def clear(self):
        self.tm = BlankTable()
        self.setModel(self.tm)
        #self.setRTable('matrix("")')
        self.criteriaList = {}
    def headerClicked(self,val):
        
        selectedCol = self.horizontalHeader().logicalIndexAt(val) + 1
        #self.tm.createMenu(selectedCol)
        self.createMenu(selectedCol)
    def getData(self,row,col):
        if not self.tm: return False
        return self.tm.data(self.tm.createIndex(row,col),Qt.DisplayRole).toString()
    def createMenu(self, selectedCol):
        self.tm.createMenu(selectedCol)
        
    def clearFiltering(self):
        if self.tm:
            self.tm.clearFiltering()
        
    def getFilteredData(self):
        try:
            return self.tm.getFilteredData()
        except:
            return None
        
        
    def getSettings(self):
        # print '############################# getSettings'
        if self.selectionModel():
    
          selections = [(x.top(),x.left(),x.bottom(),x.right()) for x in self.selectionModel().selection()]
        else:
            selections = None
        #import cPickle
        r = {
        'signal': self.tm.signal.saveSettings(),
        'modelSettings': self.tm.getSettings(),
        'class':unicode(self.tm.__class__),
        'criteriaList': self.criteriaList,
        'selection2':selections
        }
        
        if self.sortIndex:
            r['sortIndex'] = self.sortIndex
        
        # print r
        return r
    def startProgressBar(self, title,text,max):
        progressBar = QProgressDialog()
        progressBar.setCancelButtonText(QString())
        progressBar.setWindowTitle(title)
        progressBar.setLabelText(text)
        progressBar.setMaximum(max)
        progressBar.setValue(0)
        progressBar.show()
        return progressBar
        
    def loadSettings(self,data):
        # print _('loadSettings for a filter table')
        # print data
        if not data: return
        if 'Rdata' not in data:
            if data['modelSettings'] == None: 
                print 'modelsettings not found'
                return
            
            print 'loading with 1.90 settings'
            print data['modelSettings']
            if 'class' not in data:
                redRLog.log(redRLog.REDRCORE, redRLog.WARNING, 'the class attribute is not found in the data %s' % str(data))
                return
            #import imp, redRObjects
            #fp, pathname, description = imp.find_module('libraries', [redREnviron.directoryNames['redRDir']])
            #varc = imp.load_module('libraries', fp, pathname, description)
            
            #for mod in data['class'].replace("<'", '').replace("'>", '').split('.')[1:]:
            #    varc = getattr(varc, mod)
            # Get the widget and instantiate a data table signal that will then generate the table model for us.
            #self.tm = varc(redRObjects.getWidgetInstanceByID(data['modelSettings']['parentWidget']), **data['modelSettings'])
            import redRObjects
            signal = redRObjects.signalFromSettings(data['signal'])
            self.tm = signal.getTableModel(self, self.filterable, self.sortable)
            #self.setTable(var, filterable = self.filterable, sortable = self.sortable) 
            
            self.setModel(self.tm)
            self.dataInfo.setText(self.tm.getSummary())
            selModel = self.selectionModel()
            # print selModel
            
            if 'selection2' in data.keys() and len(data['selection2']):
                for x in data['selection2']:
                    selModel.select( QItemSelection(self.tm.createIndex(x[0],x[1]),self.tm.createIndex(x[2],x[3])),QItemSelectionModel.Select)
                    
        elif data['Rdata'] == None:
            self.clear()
        else:
            redRLog.log(redRLog.REDRCORE, redRLog.WARNING, 'DEPRICATION WARNING. Filter table loading of 1.85 settings will not be available in 2.0.  Please resave your old files using these settings before upgrading to 2.0')
            from libraries.base.signalClasses.RDataFrame import RDataFrameModel
            self.tm = RDataFrameModel(parent = self, Rdata = data['Rdata'], filterable=self.filterable, sortable=self.sortable)
            self.setModel(self.tm)
            self.dataInfo.setText(self.tm.getSummary())
            
            #self.Rdata = data['Rdata']
            #self.criteriaList = data['criteriaList']
            ## print 'filtering data on the following criteria %s' % unicode(self.criteriaList)
            #self.filter()

            #if 'sortIndex' in data.keys():
                #self.sortByColumn(data['sortIndex'][0],data['sortIndex'][1])
            selModel = self.selectionModel()
            ## print selModel
            
            if 'selection2' in data.keys() and len(data['selection2']):
                for x in data['selection2']:
                    selModel.select( QItemSelection(self.tm.createIndex(x[0],x[1]),self.tm.createIndex(x[2],x[3])),QItemSelectionModel.Select)
            
            
            if 'selection' in data.keys() and selection and len(data['selection']):
                progressBar = self.startProgressBar(_('Filter Table Loading'), _('Loading Fiter Table'), 50)

                if len(data['selection']) > 1000:
                    mb = QMessageBox.question(None, _('Setting Selection'), _('There are more than 1000 selections to set for %s,\ndo you want to discard them?\nSetting may take a very long time.') % self.label, QMessageBox.Yes, QMessageBox.No)
                    if mb.exec_() == QMessageBox.No:
                    
                        progressBar.setLabelText(_('Loading Selections'))
                        progressBar.setMaximum(len(data['selection']))
                        progressBar.setValue(0)
                        val = 0
                        for i in data['selection']:
                            selModel.select(self.tm.createIndex(i[0],i[1]),QItemSelectionModel.Select)
                            val += 1
                            progressBar.setValue(val)
                progressBar.hide()
                progressBar.close()
     
    def delete(self):
        sip.delete(self)
    def getReportText(self, fileDir):
        if self.getFilteredData():
            limit = min(self.tm.rowCount(self),50)
            # import time
            # start = time.time()
            # print 'start'
            data = self.R('as.matrix(%s[1:%d,])'% (self.getFilteredData(),limit))
            # print 'stop', time
            colNames = self.R('colnames(%s)' % self.getFilteredData())
            # text = redRReports.createTable(data, columnNames = colNames)
            return {self.widgetName:{'includeInReports': self.includeInReports, 'type':'table', 
            'data':data,'colNames': colNames,
            'numRowLimit': limit}}

        else:
            return {self.widgetName:{'includeInReports': self.includeInReports, 'text':''}}