예제 #1
0
 def update_TView(self):
     if self.selected_id in self.layers.keys():
         self.dockwidget.layersBox.enabled = False
         attrs_names = [u"Идентификатор",u"Наименование",u"Описание",u"Условный знак"]
         attrs_values = []
         lif = self.iface.legendInterface()
         lyrs = lif.layers()
         for lyr in lyrs:
             all_case = (self.selected_id == '0' and lif.isLayerVisible(lyr))
             if isinstance(lyr, QgsVectorLayer) and (lyr.id() == self.selected_id or all_case):
                 #attrs_names = [a.name() for a in lyr.fields()]
                 features = lyr.getFeatures()
                 attrs_values += [[feat[i] for i in xrange(len(attrs_names))] for feat in features]
                 if not all_case:
                     break
         self.dockwidget.tableView.setRowCount(len(attrs_values))
         self.dockwidget.tableView.setColumnCount(len(attrs_names))
         self.dockwidget.tableView.setHorizontalHeaderLabels(attrs_names)
         for row in xrange(len(attrs_values)):
             for col in xrange(len(attrs_names)):
                 if col < len(attrs_names) - 1:
                     item = QTableWidgetItem(u'%s' % attrs_values[row][col])
                 else:
                     pm = self.get_sign_image(attrs_values[row][col])
                     if pm:
                         item = QTableWidgetItem(self.config["signs"][attrs_values[row][col]].get("alias",""))
                         item.setData(Qt.DecorationRole, pm.scaled(20, 20))
                     else:
                         item = QTableWidgetItem(u'%s' % attrs_values[row][col])
                 self.dockwidget.tableView.setItem(row,col,item)
         self.dockwidget.layersBox.enabled = True
예제 #2
0
 def addMachine(self,name,ip,status=''):
     for row in self.machinesData.values:
         if row.has_key('nameItem'):
             if row['nameItem'] == name:
                 isAlive = True
         else:
             rowNumber = self.tbl.rowCount()
             nameItem = QTableWidgetItem(name)
             IPItem = QTableWidgetItem(self.machinesData[name])
             statusItem = QTableWidgetItem(status)
             checkboxItem = QTableWidgetItem()
             checkboxItem.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable)
             checkboxItem.setCheckState(Qt.Checked)
             transferItem = QTableWidgetItem('')
             self.allItemsChecked = True
             self.tbl.insertRow(rowNumber)
             self.tbl.setItem(rowNumber,NAME,nameItem)
             self.tbl.setItem(rowNumber,IP,IPItem)
             self.tbl.setItem(rowNumber,STATUS,statusItem)
             self.tbl.setItem(rowNumber,CHECKED,checkboxItem)
             self.tbl.setItem(rowNumber,TRANSFER,transferItem)
             self.machinesData[rowNumber] = {'checkboxItem':checkboxItem,
                                             'nameItem':nameItem,
                                             'IPItem':IPItem,
                                             'statusItem':statusItem,
                                             'transferItem':transferItem}
             row = self.machinesData[rowNumber]
             isAlive = None
         self.emit(SIGNAL('updateStatus'),row,isAlive)
     return
예제 #3
0
def append_row(table, label, data):
    """Append new row to table widget.

    :param table: The table that shall have the row added to it.
    :type table: QTableWidget

    :param label: Label for the row.
    :type label: str

    :param data: custom data associated with label value.
    :type data: QVariant
    """
    myRow = table.rowCount()
    table.insertRow(table.rowCount())

    myItem = QTableWidgetItem(label)

    # see for details of why we follow this pattern
    # http://stackoverflow.com/questions/9257422/
    # how-to-get-the-original-python-data-from-qvariant
    # Make the value immutable.
    myVariant = QVariant((data,))
    # To retrieve it again you would need to do:
    #myValue = myVariant.toPyObject()[0]
    myItem.setData(Qt.UserRole, myVariant)

    table.setItem(myRow, 0, myItem)
    table.setItem(myRow, 1, QTableWidgetItem(''))
예제 #4
0
파일: modif_index.py 프로젝트: halbbob/dff
    def load_items(self):
        """
        Load items from the indexed_items list and add them in the
        self.indexedItems QTableWidget.
        """
        count = 0

        # get the list of already indexed stuff and add them in the qtablewidget
        # with a not-editable check box indicating if it has been indexed
        # recursively or not
        for i in self.indexed_items:
            node = VFS.Get().getNodeFromPointer(long(i))
            if node == None:
                continue
            recurse = self.indexed_items[i]

            new_item = QTableWidgetItem(QIcon(":/folder.png"), node.name())
            self.indexedItems.setRowCount(count + 1)
            new_item.setData(Qt.UserRole + 1, QVariant(long(node.this)))

            self.indexedItems.setItem(count, 0, new_item)

            new_item2 = QTableWidgetItem()
            new_item2.setFlags(Qt.ItemIsUserCheckable)
            if recurse:
                new_item2.setCheckState(Qt.Checked)
            else:
                new_item2.setCheckState(Qt.Unchecked)
            self.indexedItems.setItem(count, 1, new_item2)
            count += 1
        return count
예제 #5
0
    def load_words(self):
        dictionary = self.dictionaries[self.dict_combo.currentIndex()]
        words = Word.objects.filter(dictionary=dictionary.abbrev) \
                    .order_by('original')
        paginator = Paginator(words, self.row, allow_empty_first_page=True)
        try:
            page_obj = paginator.page(self.page_number)
        except InvalidPage:
            return

        self.words_table.clear()
        self.words_table.setRowCount(len(page_obj.object_list))

        self.words_table.setHorizontalHeaderLabels(['Original',
                                                    'Translation',
                                                    'Parts of Speech',
                                                    'Phoneme',
                                                    'Synonyms',
                                                    'Antonyms',
                                                    'Added at',
                                                    'Status'
                                                   ])

        for i, word in enumerate(page_obj.object_list):
            for j, cell in enumerate([word.original, word.translation, word.pos,
                                     word.phoneme, word.synonyms, word.antonyms,
                                     word.added_at.strftime("%Y-%m-%d %H:%M"),
                                      "exported" if word.exported else "new"]):
                item = QTableWidgetItem(cell)
                item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                self.words_table.setItem(i, j, item)

        self.next_button.setEnabled(page_obj.has_next())
        self.previous_button.setEnabled(page_obj.has_previous())
예제 #6
0
    def restoreWidgetPosition(self):
        super().restoreWidgetPosition()

        self.table = QTableWidget(self.harmonic_maximum_index + 1, 3)
        self.table.setAlternatingRowColors(True)
        self.table.horizontalHeader().setResizeMode(QHeaderView.Fixed)

        for i in range(0, 3):
            self.table.setColumnWidth(i, 70)

        horHeaders = []
        verHeaders = []

        for n, key in enumerate(sorted(self.data.keys())):
            horHeaders.append(key)

            for m, item in enumerate(self.data[key]):
                table_item = QTableWidgetItem(str(item))
                table_item.setTextAlignment(Qt.AlignRight)
                self.table.setItem(m, n, table_item)
                verHeaders.append(str(m))

        self.table.setHorizontalHeaderLabels(horHeaders)
        self.table.setVerticalHeaderLabels(verHeaders)
        self.table.resizeRowsToContents()

        self.table.itemChanged.connect(self.table_item_changed)

        self.scrollarea.setWidget(self.table)
        self.scrollarea.setWidgetResizable(1)

        gui.rubber(self.controlArea)
예제 #7
0
    def on_create_super_group(self):
        inames = [iname for iname, check in enumerate(self.checks)
                  if bool(check.checkState())]

        if not len(inames):
            # TODO: add logging
            print('nothing is checked...')
            return
        if inames[0] == 0:
            # TODO: add logging
            print("cannot include 'ALL' in supergroup...")
            return

        name = 'SuperGroup'
        # popup gui and get a name

        irow = self.table.rowCount()
        self.table.insertRow(irow)


        check = QTableWidgetItem()
        check.setCheckState(False)
        name_text = QTableWidgetItem(str(name))

        self.names.extend(name)
        self.names_text.append(name_text)
        self.checks.append(check)

        self.table.setItem(irow, 0, check)
        self.table.setItem(irow, 1, name_text)
    def on_pbnRemoveIndicator_clicked(self):
        row = self.twIndicatorsToVisualize.currentRow()

        cur_item = self.twIndicatorsToVisualize.item(row, 0)
        if cur_item is not None:
            value = str(cur_item.text())

            item = QTableWidgetItem(value) #need to create new item because QT deletes object
            last_row = self.twAvailableIndicators.rowCount()
            indicator = self.indicator_nodes[value]
            new_row = QTableWidgetItem()
            self.twAvailableIndicators.setRowCount(last_row + 1)
            self.twAvailableIndicators.setVerticalHeaderItem(last_row,new_row)

            self.twAvailableIndicators.setItem(last_row,0,item)

            item = QTableWidgetItem()
            item.setText(indicator.text or '')
            self.twAvailableIndicators.setItem(last_row,1,item)

#            item = QTableWidgetItem()
#            item.setText(indicator['value'])
#            self.twAvailableIndicators.setItem(last_row,2,item)

        self.twIndicatorsToVisualize.removeRow(row)
예제 #9
0
    def __init__(self, parent = None, datalist = None, mode='r'):
        super(SimpleListDlg, self).__init__(parent)
        self.tbl = QTableWidget()
        self.mode = mode # read only or write 'r'/'w'
        self.values = []
        if datalist is not None:
            data = datalist.toList()
            self.tbl.setRowCount(len(data))
            self.tbl.setColumnCount(1)
            for i,val in enumerate(data):
                #print i, val.toFloat()
                self.values.append(val.toFloat()[0])
                it = QTableWidgetItem("%g" % val.toFloat()[0])
                if self.mode == 'r': 
                    it.setFlags(it.flags() & ~Qt.ItemIsEditable)
                self.tbl.setItem(i,0,it)
        
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|
                                     QDialogButtonBox.Cancel)
        layout = QVBoxLayout()
        layout.addWidget(self.tbl)
        layout.addWidget(buttonBox)
        self.setLayout(layout)

        self.connect(buttonBox, SIGNAL("accepted()"), self.accept)
        self.connect(buttonBox, SIGNAL("rejected()"), self.reject)
예제 #10
0
 def add_peer(self, peer):
     rows = self.table_peers.rowCount()
     self.table_peers.insertRow(rows)
     item = QTableWidgetItem(peer.nickname)
     item.peer = peer
     self.table_peers.setItem(rows, 0, item)
     self.table_peers.setItem(rows, 1, QTableWidgetItem(peer.ip))
예제 #11
0
 def add_to_table(self, table, row, row_list, set_enabled=True, color=[255, 255, 255]):
     for col in range(len(row_list)):
         item = QTableWidgetItem(str(row_list[col]))
         if set_enabled:
             item.setFlags(QtCore.Qt.ItemIsEnabled)
         table.setItem(row, col, item)
         table.item(row, col).setBackground(QtGui.QColor(color[0], color[1], color[2]))
예제 #12
0
 def addRequest(self, widget=None):
   currow = self.rowCount()
   self.setRowCount(self.rowCount() + 1)
   # Add conjonctions if not First widget
   if len(self.fieldMapper) != 0:
     conjonction = ConjonctionCombo(self)
     self.setCellWidget(currow, 0, conjonction)
     self.horizontalHeader().setResizeMode(0, QHeaderView.ResizeToContents)
   else:
     empty = QTableWidgetItem(QString(""))
     empty.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
     self.setItem(currow, 0, empty)
   # Add Field choice
   fields = FieldCombo(self)
   self.connect(fields, SIGNAL("fieldChanged"), self.changeFilterType)
   self.setCellWidget(currow, 1,  fields)
   self.fieldMapper.append(fields.fieldCombo)
   # Add Widget
   if widget == None:
     widget = NameRequest(self)
   self.setCellWidget(currow, 2, widget)
   # Add request button
   add = self.createAddRequestButton()
   self.setCellWidget(currow, 3, add)
   # Remove request button
   rm = removeRequestButton()
   self.removeMapper.append(rm)
   self.connect(rm, SIGNAL("removeRequest"), self.removeRequest)
   self.setCellWidget(currow, 4, rm)
예제 #13
0
    def add_new_table(self, rel, name):
        import itertools

        table = QTableWidget()
        table.setRowCount(0)
        table.setColumnCount(0)

        data = itertools.chain([rel.fields], rel.content)

        for row_data in data:
            row = table.rowCount()
            table.setColumnCount(len(row_data))
            for col, text in enumerate(row_data):
                item = QTableWidgetItem()
                item.setText(text)
                if row == 0:
                    table.setHorizontalHeaderItem(col, item)
                else:
                    table.setItem(row - 1, col, item)
            table.insertRow(row)
        table.removeRow(table.rowCount() - 1)
        self.stacked.addWidget(table)
        self.stacked.setCurrentIndex(self.stacked.count() - 1)
        lateral = Pireal.get_service("lateral")
        lateral.add_item_list([name])
예제 #14
0
    def initTable(self):
        # stop the update timer
        self.timerDataRequest.stop()

        # init servo memory data table
        self.tableServoData.clear()
        self.tableServoData.setColumnCount(1)
        self.tableServoData.setHorizontalHeaderItem(0, QTableWidgetItem('Parameter'))
        self.tableServoData.setRowCount(len(self.serialProtocol.memoryInfo['fieldNames']))
        rowNumber = 0
        for fieldName in self.serialProtocol.memoryInfo['fieldNames']:
            fieldInfo = self.serialProtocol.memoryInfo[fieldName]
            nameItem = QTableWidgetItem(fieldInfo['name'])
            if fieldInfo['writable']:
                nameItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            else:
                nameItem.setFlags(Qt.ItemFlag())
            self.tableServoData.setItem(rowNumber, 0, nameItem)
            self.tableServoData.resizeRowToContents(rowNumber)
            self.tableServoData.setRowHeight(rowNumber, self.tableServoData.rowHeight(rowNumber) - 7)
            rowNumber += 1
        self.tableServoData.resizeColumnToContents(0)

        # restart the update timer
        self.timerDataRequest.start(20)
예제 #15
0
    def updateTable(self, rhive, key):
        self.resetTable()
        values = key.values
        for value in values:
            currow = self.rowCount()
            self.setRowCount(self.rowCount() + 1)
            if value.name:
                name = value.name
            else:
                name = "(Default)"
            #          item_name = valueItem(value.fetch_data(), key.name)

            #          item_name = QTableWidgetItem(QString.fromUtf8(name))
            #          item_name.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
            item_name = valueItem(name, key.name)

            item_type = QTableWidgetItem(QString(regtype[value.type]))
            item_type.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

            item_data = valueItem(value.fetch_data(), key.name)
            # QTableWidgetItem(self.dataToQString(value.fetch_data()))
            #          item_data.setFlags(Qt.ItemIsSelectable|Qt.ItemIsEnabled)
            self.setItem(currow, 0, item_name)
            self.setItem(currow, 1, item_type)
            self.setItem(currow, 2, item_data)
        del (rhive)
예제 #16
0
파일: database.py 프로젝트: Fapiko/pyHeidi
	def setAsCurrentDatabase(self):
		if len(self.tables) == 0:
			self.refreshTables()

		self.applicationWindow.showDatabaseTab()
		mainWindow = self.applicationWindow.mainWindow
		databaseTab = mainWindow.databaseTab
		twMachineTabs = mainWindow.twMachineTabs
		twMachineTabs.setTabText(twMachineTabs.indexOf(databaseTab), "Database: %s" % self.name)
		twMachineTabs.setCurrentWidget(databaseTab)

		databaseTable = mainWindow.databaseInfoTable
		for i in reversed(range(databaseTable.rowCount())):
			databaseTable.removeRow(i)

		for table in self.tables:
			index = databaseTable.rowCount()
			databaseTable.insertRow(index)
			nameItem = QTableWidgetItem(table.name)
			nameItem.setIcon(QIcon('../resources/icons/table.png'))
			databaseTable.setItem(index, 0, nameItem)
			databaseTable.setItem(index, 1, QTableWidgetItem(str(table.rows)))
			databaseTable.setItem(index, 2, QTableWidgetItem(byteSizedStrings(table.size)))
			databaseTable.setItem(index, 3, QTableWidgetItem(table.getCreateTime()))
			databaseTable.setItem(index, 4, QTableWidgetItem(table.getUpdatedTime()))
			databaseTable.setItem(index, 5, QTableWidgetItem(table.engine))
			databaseTable.setItem(index, 6, QTableWidgetItem(table.comment))
			databaseTable.setItem(index, 7, QTableWidgetItem('table'))

		self.applicationWindow.tableTab.populateDefaultCollationField(self.server)
예제 #17
0
	def loadSentencesInTable(self):
		self.col = 0
		if len(self.sentenceList) > 0:
			self.sentenceTable.setRowCount(len(self.sentenceList))
			cellList = []
			## Create QTableWidgetItems from the sentence list
			for sentence in self.sentenceList:
				item = QTableWidgetItem(QString(sentence))
				item.setFlags(Qt.ItemFlags(Qt.ItemIsSelectable |
								Qt.ItemIsUserCheckable | Qt.ItemIsEnabled))
				item.setCheckState(Qt.Unchecked)
				cellList.append(item)
			cellList.reverse()
			# set the widget items in the table
			for item in range(0, len(self.sentenceList)):
				self.sentenceTable.setItem(item, self.col, cellList.pop())
			
			for index in range(0, len(self.sentenceList)):
				self.sentenceTable.verticalHeader().resizeSection(index, 100)
			
			if len(self.sentenceList) == 5:
				self.sentenceTable.setFixedHeight(500)
			if len(self.sentenceList) == 4:
				self.sentenceTable.setFixedHeight(400)
			elif len(self.sentenceList) == 3:
				self.sentenceTable.setFixedHeight(300)
			elif len(self.sentenceList) == 2:
				self.sentenceTable.setFixedHeight(200)
			elif len(self.sentenceList) == 1:
				self.sentenceTable.setFixedHeight(100)
		else:
			self.sentenceTable.clearContents()
예제 #18
0
    def __init__(self, data, keyname):
        QTableWidgetItem.__init__(self)
        self.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        self.data = data
        self.keyname = keyname

        self.setText(self.dataToQString(self.data))
예제 #19
0
    def reload_harmonics_table(self):
        horHeaders = []
        verHeaders = []

        self.table.itemChanged.disconnect(self.table_item_changed)

        self.table.clear()

        row_count = self.table.rowCount()

        for n in range(0, row_count):
            self.table.removeRow(0)

        for index in range(0, self.harmonic_maximum_index + 1):
            self.table.insertRow(0)

        for n, key in enumerate(sorted(self.data.keys())):
            horHeaders.append(key)

            for m, item in enumerate(self.data[key]):
                table_item = QTableWidgetItem(str(item))
                table_item.setTextAlignment(Qt.AlignRight)
                self.table.setItem(m, n, table_item)
                verHeaders.append(str(m))

        self.table.setHorizontalHeaderLabels(horHeaders)
        self.table.setVerticalHeaderLabels(verHeaders)

        self.table.resizeRowsToContents()

        for i in range(0, 3):
            self.table.setColumnWidth(i, 70)

        self.table.itemChanged.connect(self.table_item_changed)
예제 #20
0
def append_row(table, label, data):
    """Append new row to table widget.

    :param table: The table that shall have the row added to it.
    :type table: QTableWidget

    :param label: Label for the row.
    :type label: str

    :param data: custom data associated with label value.
    :type data: str
    """
    # noinspection PyUnresolvedReferences
    count = table.rowCount()
    # noinspection PyUnresolvedReferences
    table.insertRow(table.rowCount())

    items = QTableWidgetItem(label)

    # see for details of why we follow this pattern
    # http://stackoverflow.com/questions/9257422/
    # how-to-get-the-original-python-data-from-qvariant
    # Make the value immutable.
    variant = (data,)
    # To retrieve it again you would need to do:
    # value = myVariant.toPyObject()[0]
    items.setData(Qt.UserRole, variant)

    # noinspection PyUnresolvedReferences
    table.setItem(count, 0, items)
    # noinspection PyUnresolvedReferences
    table.setItem(count, 1, QTableWidgetItem(''))
예제 #21
0
 def iconChooser(self):
     ' Choose a Icon and copy it to clipboard '
     #
     from .std_icon_naming import std_icon_naming as a
     #
     prv = QDialog(self.dock)
     prv.setWindowFlags(Qt.FramelessWindowHint)
     prv.setAutoFillBackground(True)
     prv.setGeometry(self.fileView.geometry())
     table = QTableWidget(prv)
     table.setColumnCount(1)
     table.setRowCount(len(a))
     table.verticalHeader().setVisible(True)
     table.horizontalHeader().setVisible(False)
     table.setShowGrid(True)
     table.setIconSize(QSize(128, 128))
     for index, icon in enumerate(a):
         item = QTableWidgetItem(QIcon.fromTheme(icon), '')
         # item.setData(Qt.UserRole, '')
         item.setToolTip(icon)
         table.setItem(index, 0, item)
     table.clicked.connect(lambda: QApplication.clipboard().setText(
       'QtGui.QIcon.fromTheme("{}")'.format(table.currentItem().toolTip())))
     table.doubleClicked.connect(prv.close)
     table.resizeColumnsToContents()
     table.resizeRowsToContents()
     QLabel('<h3> <br> 1 Click Copy, 2 Clicks Close </h3>', table)
     table.resize(prv.size())
     prv.exec_()
예제 #22
0
파일: gui.py 프로젝트: testmana2/profitpy
    def __init__(self):
        """ Constructor.

        """
        QTableWidgetItem.__init__(self, self.UserType)
        self.setFlags(self.flags() & ~Qt.ItemIsEditable)
        self.value = None
예제 #23
0
 def __setTableItem(self, table, row, col, text):
     item = table.item(row, col)
     if item:
         item.setText(text)
     else:
         newitem = QTableWidgetItem(text)
         newitem.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable)
         table.setItem(row, col, newitem)    
예제 #24
0
 def changeHabColor(self):
     currRow = self.habTableWidget.currentRow()
     color_item = QTableWidgetItem()
     new_qcolor = QColorDialog.getColor(parent=self)
     if new_qcolor.isValid():
         color_item.setBackgroundColor( new_qcolor )
         color_item.setText( new_qcolor.name() )
         self.habTableWidget.setItem(currRow,2,color_item)
예제 #25
0
	def generateIdField(id=''):
		"""
		@rtype: QTableWidgetItem
		"""
		idField = QTableWidgetItem(str(id))
		idField.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
		idField.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

		return idField
예제 #26
0
 def finish_init(self, data):
     self.data = data
     for c, col in enumerate(ColumnHeaders):
         self.insertColumn(c)
         item = QTableWidgetItem(col)
         font = item.font()
         font.setPointSize(font.pointSize() - 2)
         item.setFont(font)
         self.setHorizontalHeaderItem(c, item)
     self.adjustSize()
예제 #27
0
 def __init__(self, sigma, name=None):
     QTableWidgetItem.__init__(self)
     # init
     # ------------------------------------------------
     self.sigma = sigma
     self.pixmapSize = QSize(61, 61)
     if not name:
         self.setNameAndBrush(self.sigma)
     else:
         self.setText(name)
예제 #28
0
 def onBtnSearchClicked(self, checked=False):
     handleSubstr = self.txtSearch.text()
     if handleSubstr:
         results = self.model.findHandlesBySubstr(handleSubstr)
         self.tblResults.setRowCount(len(results))
         for row, res in enumerate(results):
             for col, prop in enumerate(res):
                 item = QTableWidgetItem(str(prop))
                 item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
                 self.tblResults.setItem(row, col, item)
예제 #29
0
    def setTableContent(self):
        params = self._alg.parameters
        outputs = self._alg.outputs
        visibleParams = [p for p in params if not p.hidden]
        visibleOutputs = [p for o in outputs if not o.hidden]
        self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs))

        for i, param in visibleParams:
            item = QTableWidgetItem(param.description)
            item.setFlags(Qt.ItemIsEnabled)
            self.tableWidget.setItem(i, 0, item)
            item = self.getWidgetFromParameter(param)
            self.valueItems[param.name] = item
            self.tableWidget.setCellWidget(i, 1, item)
            self.tableWidget.setRowHeight(i, 22)

        for i, output in visibleOutputs:
            item = QTableWidgetItem(output.description + '<'
                                    + output.__module__.split('.')[-1] + '>')
            item.setFlags(Qt.ItemIsEnabled)
            self.tableWidget.setItem(i, 0, item)
            item = QLineEdit()
            if hasattr(item, 'setPlaceholderText'):
                item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME)
            self.valueItems[output.name] = item
            self.tableWidget.setCellWidget(i, 1, item)
            self.tableWidget.setRowHeight(i, 22)
예제 #30
0
    def clear(self):
        self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
        self.output_text.clear()
        self.tableWidget.clear()

        self._currentTaskName = None
        self._currentTaskProgressBar = None
        self._currentTaskIncidents = None
        self._currentTaskIncidentsWidget = None
        self._currentTaskMessages = 0

        # Set up tablewidget
        self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.tableWidget.setRowCount(0);
        self.tableWidget.setColumnCount(3)
        item = QTableWidgetItem()
        item.setText('Rule')
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem()
        item.setText('Progress')
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QTableWidgetItem()
        item.setText('Incidents')
        self.tableWidget.setHorizontalHeaderItem(2, item)
        self.tableWidget.horizontalHeader().setResizeMode(QHeaderView.Stretch)
예제 #31
0
    def _setup_available_indicators(self):
        indicator_nodes = get_available_indicator_nodes(self.project)

        current_row = self.indicator_table.currentRow()

        self.indicator_table.clear()
        self.indicator_table.setColumnCount(3)
        self.indicator_table.setRowCount(len(indicator_nodes))

        col = QTableWidgetItem()
        col.setText('Name')
        self.indicator_table.setHorizontalHeaderItem(0, col)

        col = QTableWidgetItem()
        col.setText('Dataset')
        self.indicator_table.setHorizontalHeaderItem(1, col)

        col = QTableWidgetItem()
        col.setText('Definition')
        self.indicator_table.setHorizontalHeaderItem(2, col)

        for i, indicator in enumerate(indicator_nodes):
            row = QTableWidgetItem()
            self.indicator_table.setVerticalHeaderItem(i, row)

            dataset, name = get_variable_dataset_and_name(indicator)

            item = QTableWidgetItem()
            item.setText(name)
            self.indicator_table.setItem(i, 0, item)

            item = QTableWidgetItem()
            item.setText(dataset)
            self.indicator_table.setItem(i, 1, item)

            item = QTableWidgetItem()
            item.setText(indicator.text or '')
            self.indicator_table.setItem(i, 2, item)

        if current_row is None or current_row == -1:
            current_row = 0
        self.indicator_table.resizeRowsToContents()
        self.indicator_table.resizeColumnsToContents()

        self.indicator_table.setCurrentCell(current_row, 0)
        self.on_indicator_table_itemSelectionChanged()
예제 #32
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        Utils.setupLogger(logger)

        self.ui = Ui_EnergyChange()
        self.ui.setupUi(self)
        self.ui.scoretable.setSelectionMode(QAbstractItemView.SingleSelection)
        self.setWindowTitle('Energy Change!')

        # Blank out 24-7 with 3 lines on klystron complement table (it doesn't
        # exist!)
        item = QTableWidgetItem()
        item.setText('---')
        self.ui.klysCompTable.setItem(6, 3, item)

        self.ui.textBrowser.append('Energy Change Initialized. Pick a time.')

        # Button for restoring klystron complement as found in archiver;
        # want disabled initially as nothing has been loaded yet
        self.ui.restoreButton.setDisabled(True)

        Utils.setupCalendar(self.ui.calendarWidget, self.ui.timeEdit)

        # Instatiate python score class
        self.scoreObject = PyScore()

        greetingIdx = randint(0, len(Utils.greetings) - 1)
        self.ui.statusText.setText(Utils.greetings[greetingIdx])

        self.loadStyleSheet()

        self.setpoints = {}
        Utils.populateSetpoints(self.setpoints)

        self.keyLists = {}
        Utils.populateKeyLists(self.keyLists)

        self.scoreInfo = {
            "scoreStructs": [],
            "dateChosen": None,
            "timeChosen": None
        }

        self.scoreData = {}

        self.klystronComplement = {"desired": {}, "original": {}}

        self.mirrorStatus = {
            "needToChangeM1": False,
            "hardPositionNeeded": False,
            "softPositionNeeded": False,
            "needToChangeM3": False,
            "amoPositionNeeded": False,
            "sxrPositionNeeded": False
        }

        self.timestamp = {
            "requested": None,
            "archiveStart": None,
            "archiveStop": None,
            "changeStarted": None
        }

        # valsObtained is boolean representing whether user has obtained archive
        # data for selected time. Scoreproblem is a boolean representing if
        # there was a problem loading some BDES. progress keeps track of the
        # progress number (between 0 and 100)
        self.diagnostics = {
            "progress": 0,
            "valsObtained": False,
            "scoreProblem": False,
            "threads": []
        }

        # Set progress bar to zero on GUI opening
        self.ui.progbar.setValue(0)

        # Get list of recent configs and populate GUI score table
        self.getScores()
        self.makeConnections()
예제 #33
0
	def _actualizarDatosFinalizado(self, proceso, i):
		self.tablaDatos.setItem(i, 5, QTableWidgetItem(str(proceso.comienzo)))
		self.tablaDatos.setItem(i, 6, QTableWidgetItem(str(proceso.finalizacion)))
		self.tablaDatos.setItem(i, 7, QTableWidgetItem(str(proceso.finalizacion - proceso.llegada)))
		self.tablaDatos.setItem(i, 8, QTableWidgetItem(str(proceso.comienzo - proceso.llegada)))
예제 #34
0
	def _actualizarGantt(self):
		self.tablaGantt.insertColumn(self.columna)
		for i in range(len(self.contenedor)):
			item = QTableWidgetItem()
			if self.contenedor[i].ejecutando():
				if isinstance(self.contenedor, MulticolasRetro):
					if self.contenedor[i].prioridad == 1:
						item.setBackgroundColor(QColor(0,128,0))
					elif self.contenedor[i].prioridad == 2:
						item.setBackgroundColor(QColor(0,255,0))
					elif self.contenedor[i].prioridad == 3:
						item.setBackgroundColor(QColor(128,255,128))
				else:
					item.setBackgroundColor(Qt.green) 
			elif self.contenedor[i].listo():
				if isinstance(self.contenedor, MulticolasRetro):
					if self.contenedor[i].prioridad == 1:
						item.setBackgroundColor(QColor(128,0,0))
					elif self.contenedor[i].prioridad == 2:
						item.setBackgroundColor(QColor(255,0,0))
					elif self.contenedor[i].prioridad == 3:
						item.setBackgroundColor(QColor(255,128,128))
				else:
					item.setBackgroundColor(Qt.red) 
			elif self.contenedor[i].bloqueado():
				item.setBackgroundColor(Qt.blue)
			self.tablaGantt.setItem(i, self.columna, item)
		self.columna += 1
		self.tablaGantt.resizeColumnsToContents()
예제 #35
0
  def onBlockRead(self, addr_start, num_bytes, raw_bytes):
    if addr_start == self.scan_addr_start and num_bytes == self.scan_num_bytes:
      # Validate txt_value
      res = parse_dec_or_hex(self.txt_value.getValue())
      if res is None:
        self.log.emit('Failed to parse Current Value: must be either DEC or HEX format', 'red')
        return
      elif res[0] < 0:
        self.log.emit('Failed to parse Current Value: must be positive', 'red')
        return
      if self.code.num_bytes == 1:
        value_bytes = struct.pack('>B', res[0])
      elif self.code.num_bytes == 2:
        value_bytes = struct.pack('>H', res[0])
      elif self.code.num_bytes == 4:
        value_bytes = struct.pack('>I', res[0])
      else:
        self.log.emit('INTERNAL ERROR: code has %d bytes' % self.code.num_bytes, 'red')
        return

      range_bytes = str(raw_bytes)
      if self.scan_count == 0: # List matching-valued addresses in initial scan
        self.cand_addrs = []
        byte_offset = 0
        while byte_offset < num_bytes:
          addr_curr = addr_start + byte_offset
          if range_bytes[byte_offset:(byte_offset+self.code.num_bytes)] == value_bytes:
            self.cand_addrs.append(addr_curr)
          byte_offset += self.code.num_bytes

      else: # Reduce matching-valued addresses in non-initial scan
        if len(self.cand_addrs) == 0:
          self.log.emit('No more candidate addresses remaining; press Reset instead', 'red')
          return
        idx = 0
        while idx < len(self.cand_addrs):
          addr_curr = self.cand_addrs[idx]
          byte_offset = addr_curr - addr_start
          if byte_offset < 0 or (byte_offset+self.code.num_bytes) > num_bytes:
            self.log.emit('INTERNAL ERROR: byte_offset (%d) out of range [0, %d)' % (byte_offset, num_bytes-self.code.num_bytes), 'red')
            return
          if range_bytes[byte_offset:(byte_offset+self.code.num_bytes)] == value_bytes:
            idx += 1
          else:
            self.cand_addrs.pop(idx)

      # Update scan count
      if self.scan_count == 0:
        self.txt_magn.setEnabled(False)
        self.btn_upd_range.setEnabled(False)
        self.txt_range_min.setEnabled(False)
        self.txt_range_max.setEnabled(False)
      self.scan_count += 1

      # Re-populate table
      exp_rows = len(self.cand_addrs)
      num_rows = self.tbl_cand.rowCount()
      if num_rows > exp_rows:
        for idx in xrange(num_rows-1, exp_rows-1, -1):
          self.tbl_cand.removeRow(idx)
      elif num_rows < exp_rows:
        for idx in xrange(num_rows, exp_rows):
          self.tbl_cand.insertRow(idx)
      for idx in xrange(exp_rows):
        cand_addr = self.cand_addrs[idx]
        item = QTableWidgetItem('%d' % (idx+1))
        item.setTextAlignment(Qt.AlignCenter)
        self.tbl_cand.setItem(idx, 0, item)

        item = QTableWidgetItem('0x%08X' % cand_addr)
        item.setTextAlignment(Qt.AlignCenter)
        self.tbl_cand.setItem(idx, 1, item)

        offset = cand_addr - self.code.addr_base
        item = QTableWidgetItem('%d (%s)' % (offset, to_signed_hex_str(offset)))
        item.setTextAlignment(Qt.AlignCenter)
        self.tbl_cand.setItem(idx, 2, item)

      self.log.emit('Offset scan found %d candidate addresses' % len(self.cand_addrs), 'black')
 def _getCenteredTableWidgetItem(self, text):
     item = QTableWidgetItem(text)
     item.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
     return item
예제 #37
0
    def list_item_changed(self):

        p_index = self.lst_list.currentRow()

        flags = Qt.ItemFlags()
        flags != Qt.ItemIsEnabled

        # Clear table
        self.clear_table()

        self.need_to_update_graph = False
        if p_index >= 0:

            self.table.setRowCount(0)

            if self.edit_type == self.edit_patterns:
                self.current = self.params.patterns[
                    self.lst_list.currentItem().text()]
                for v in range(len(self.current.values)):

                    row_pos = self.table.rowCount()
                    self.table.insertRow(row_pos)

                    item = QTableWidgetItem(str(v))
                    item.setFlags(flags)
                    self.table.setItem(v, 0, item)
                    self.table.setItem(
                        v, 1, QTableWidgetItem(str(self.current.values[v])))

            elif self.edit_type == self.edit_curves:
                self.current = self.params.curves[
                    self.lst_list.currentItem().text()]
                for v in range(len(self.current.xs)):

                    row_pos = self.table.rowCount()
                    self.table.insertRow(row_pos)

                    self.table.setItem(
                        v, 0, QTableWidgetItem(str(self.current.xs[v])))
                    self.table.setItem(
                        v, 1, QTableWidgetItem(str(self.current.ys[v])))

                curve_type = self.current.type
                self.cbo_pump_type.setCurrentIndex(curve_type)

            # Update GUI
            self.txt_id.setText(self.current.id)
            self.txt_desc.setText(self.current.desc)

            self.update_table_headers()

            # Update graph
            self.need_to_update_graph = True
            self.update_graph()

        else:

            # No curves
            self.txt_id.setText('')
            self.txt_desc.setText('')

            # Update table and chart
            self.need_to_update_graph = False
            for v in range(self.table.columnCount()):
                self.table.setItem(v, 1, QTableWidgetItem(''))

            self.need_to_update_graph = True
            self.update_graph()
예제 #38
0
파일: database.py 프로젝트: ccszwg/pyHeidi
    def setAsCurrentDatabase(self):
        if len(self.tables) == 0:
            self.refreshTables()

        self.applicationWindow.showDatabaseTab()
        mainWindow = self.applicationWindow.mainWindow
        databaseTab = mainWindow.databaseTab
        twMachineTabs = mainWindow.twMachineTabs
        twMachineTabs.setTabText(twMachineTabs.indexOf(databaseTab),
                                 "Database: %s" % self.name)
        twMachineTabs.setCurrentWidget(databaseTab)

        databaseTable = mainWindow.databaseInfoTable
        for i in reversed(range(databaseTable.rowCount())):
            databaseTable.removeRow(i)

        for table in self.tables:
            index = databaseTable.rowCount()
            databaseTable.insertRow(index)
            nameItem = QTableWidgetItem(table.name)
            nameItem.setIcon(QIcon('../resources/icons/table.png'))
            databaseTable.setItem(index, 0, nameItem)
            databaseTable.setItem(index, 1, QTableWidgetItem(str(table.rows)))
            databaseTable.setItem(
                index, 2, QTableWidgetItem(byteSizedStrings(table.size)))
            databaseTable.setItem(index, 3,
                                  QTableWidgetItem(table.getCreateTime()))
            databaseTable.setItem(index, 4,
                                  QTableWidgetItem(table.getUpdatedTime()))
            databaseTable.setItem(index, 5, QTableWidgetItem(table.engine))
            databaseTable.setItem(index, 6, QTableWidgetItem(table.comment))
            databaseTable.setItem(index, 7, QTableWidgetItem('table'))

        self.applicationWindow.tableTab.populateDefaultCollationField(
            self.server)
예제 #39
0
    def _add_proc_to_table(self, row, proc_info):
        self.setItem(row, 0, QTableWidgetItem(str(proc_info.identifier)))
        self.item(row, 0).setTextAlignment(Qt.AlignCenter)
        self.setItem(row, 1, QTableWidgetItem(str(proc_info.name)))
        self.setItem(row, 2, QTableWidgetItem(str(proc_info.cs_overhead)))
        self.item(row, 2).setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.setItem(row, 3, QTableWidgetItem(str(proc_info.cl_overhead)))
        self.item(row, 3).setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.setItem(
            row, 4,
            QTableWidgetItem(', '.join([x.name for x in proc_info.caches])))
        penalty_item = QTableWidgetItem(str(proc_info.penalty))
        penalty_item.setFlags(penalty_item.flags()
                              ^ (Qt.ItemIsEditable | Qt.ItemIsEnabled))
        self.setItem(row, 5, penalty_item)
        self.item(row, 5).setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.setItem(row, 6, QTableWidgetItem(str(proc_info.speed)))

        for col in range(len(self._custom_fields)):
            key = self._custom_fields[col]
            if key in proc_info.data and proc_info.data[key] is not None:
                item = QTableWidgetItem(str(proc_info.data[key]))
            else:
                item = QTableWidgetItem('')
            item.setBackgroundColor(QColor.fromRgb(200, 255, 200))
            self.setItem(row, col + len(self._header), item)
예제 #40
0
파일: qtdemo.py 프로젝트: noke8868/vnpy

if (__name__ == '__main__'):
    app = None
    if (QApplication.instance() is None):
        app = QApplication([])

    widget = QTableWidget()
    widget.setWindowFlags(Qt.Dialog)
    widget.setSortingEnabled(True)

    widget.setRowCount(50)
    widget.setColumnCount(3)
    for row in range(50):
        # create a normal QTableWidgetItem
        a = QTableWidgetItem()
        a.setText(str(row))
        widget.setItem(row, 0, a)

        # create a proper sorted item
        b = QTableWidgetItem()
        b.setData(Qt.EditRole, QVariant(row))
        widget.setItem(row, 1, b)

        # create a custom sorted item
        c = MyTableWidgetItem()
        c.setData(Qt.EditRole, QVariant(row))
        widget.setItem(row, 2, c)

    widget.show()
    if (app):
예제 #41
0
    def view(self):
        """create view and import layers"""
        layer = QgsMapLayerRegistry.instance().mapLayer(self.current_layers[0])
        uri = QgsDataSourceURI(layer.source())
        mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema())
        schema = mtch.group(1)
        assert (schema)
        dlg = QDialog()
        layout = QVBoxLayout(dlg)
        button_box = QDialogButtonBox(dlg)
        button_box.setStandardButtons(QDialogButtonBox.Cancel
                                      | QDialogButtonBox.Ok)
        button_box.accepted.connect(dlg.accept)
        button_box.rejected.connect(dlg.reject)

        user_msg1 = QgsMessageBar(dlg)
        user_msg1.pushInfo(
            "Select:", "one [many] for single [multiple] "
            "revisions.  Fetching may take time.")

        pcur = versioning_base.Db(psycopg2.connect(self.pg_conn_info()))
        pcur.execute("SELECT rev, commit_msg, branch, date, author "
                     "FROM " + schema + ".revisions")
        revs = pcur.fetchall()
        pcur.close()
        tblw = QTableWidget(dlg)
        tblw.setRowCount(len(revs))
        tblw.setColumnCount(6)
        tblw.setSortingEnabled(True)
        tblw.setHorizontalHeaderLabels([
            'Select', 'Revision', 'Commit Message', 'Branch', 'Date', 'Author'
        ])
        tblw.verticalHeader().setVisible(False)
        for i, rev in enumerate(revs):
            for j, item in enumerate(rev):
                chkBoxItem = QTableWidgetItem()
                chkBoxItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                chkBoxItem.setCheckState(Qt.Unchecked)
                tblw.setItem(i, 0, chkBoxItem)
                tblw.setItem(i, j + 1, QTableWidgetItem(str(item)))

        layout.addWidget(user_msg1)
        layout.addWidget(tblw)
        layout.addWidget(button_box)
        dlg.resize(650, 300)
        if not dlg.exec_():
            return

        rows = set()
        revision_number_list = []
        for i in range(len(revs)):
            if tblw.item(i, 0).checkState():
                print "Revision " + str(i + 1) + " will be fetched"
                revision_number_list.append(i + 1)
                rows.add(tblw.item(i, 0).row())

        progressMessageBar = self.iface.messageBar().createMessage(
            "Querying "
            "the database for revision(s) " + str(revision_number_list))
        progress = QProgressBar()
        progress.setMaximum(len(rows))
        progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress)
        self.iface.messageBar().pushWidget(progressMessageBar,
                                           self.iface.messageBar().INFO)
        progress.setValue(0)

        for i, row in enumerate(rows):
            progress.setValue(i + 1)
            branch = revs[row][2]
            rev = revs[row][0]
            versioning_base.add_revision_view(uri.connectionInfo(), schema,
                                              branch, rev)
            grp_name = branch + ' revision ' + str(rev)
            grp_idx = self.iface.legendInterface().addGroup(grp_name)
            for layer_id in reversed(self.current_layers):
                layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)
                new_uri = QgsDataSourceURI(layer.source())
                new_uri.setDataSource(
                    schema + '_' + branch + '_rev_' + str(rev),
                    new_uri.table(), new_uri.geometryColumn(), new_uri.sql(),
                    new_uri.keyColumn())
                display_name = QgsMapLayerRegistry.instance().mapLayer(
                    layer_id).name()
                src = new_uri.uri().replace('()', '')
                new_layer = self.iface.addVectorLayer(src, display_name,
                                                      'postgres')
                self.iface.legendInterface().moveLayer(new_layer, grp_idx)
        self.iface.messageBar().clearWidgets()
예제 #42
0
    def __init__(self, feature, parent=None, featureState=Qt.Unchecked):
        QTableWidgetItem.__init__(self, parent)

        self.isRootNode = False
        self.children = []
        self.featureState = featureState
예제 #43
0
    def _gotRevision(self, backend, revision):
        """ Callback for loadHistory's QtDo """
        if not backend:
            # The last revision has been processed
            self.process = None
            self.ui.loadHistoryButton.setEnabled(True)
            self.ui.loadHistoryButton.setText("Reload")
            return

        # we set the flags to Qt.ItemIsEnabled so that the items
        # are not modifiable (they are modifiable by default)
        item_revision = QTableWidgetItem(revision.id)
        item_revision.setFlags(Qt.ItemIsEnabled)

        item_time = QTableWidgetItem(
            revision.timestamp.strftime('%Y-%m-%d %H:%M:%S'))
        item_time.setFlags(Qt.ItemIsEnabled)

        item_author = QTableWidgetItem(revision.author)
        item_author.setFlags(Qt.ItemIsEnabled)

        item_summary = QTableWidgetItem(revision.comment)
        item_summary.setFlags(Qt.ItemIsEnabled)

        row = self.ui.historyTable.currentRow() + 1
        self.ui.historyTable.insertRow(row)
        self.ui.historyTable.setItem(row, 0, item_revision)
        self.ui.historyTable.setItem(row, 1, item_time)
        self.ui.historyTable.setItem(row, 2, item_author)
        self.ui.historyTable.setItem(row, 3, item_summary)

        self.ui.historyTable.setCurrentCell(row, 0)
예제 #44
0
 def updatetable2(self):
     for l in range(len(self.LCZs)): 
         if (l<10):
             iperv=float(self.dlg.tableWidget.item(0,l).text())+float(self.dlg.tableWidget.item(1,l).text())
             if (self.dlg.comboBox_27.currentText()==self.urbanchoices[0] ):
                 self.dlg.tableWidget.setItem(2,l, QTableWidgetItem(str(1.-iperv)))
                 self.dlg.tableWidget.setItem(3,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(4,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(5,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(6,l, QTableWidgetItem(str(0.00)))
             if (self.dlg.comboBox_27.currentText()==self.urbanchoices[1] ):
                 self.dlg.tableWidget.setItem(3,l, QTableWidgetItem(str(1.-iperv)))
                 self.dlg.tableWidget.setItem(2,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(4,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(5,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(6,l, QTableWidgetItem(str(0.00)))
             if (self.dlg.comboBox_27.currentText()==self.urbanchoices[2] ):
                 self.dlg.tableWidget.setItem(4,l, QTableWidgetItem(str(1.-iperv)))
                 self.dlg.tableWidget.setItem(2,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(3,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(5,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(6,l, QTableWidgetItem(str(0.00)))
             if (self.dlg.comboBox_27.currentText()==self.urbanchoices[3] ):
                 self.dlg.tableWidget.setItem(5,l, QTableWidgetItem(str(1.-iperv)))
                 self.dlg.tableWidget.setItem(2,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(3,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(4,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(6,l, QTableWidgetItem(str(0.00)))
             if (self.dlg.comboBox_27.currentText()==self.urbanchoices[4] ):
                 self.dlg.tableWidget.setItem(6,l, QTableWidgetItem(str(1.-iperv)))
                 self.dlg.tableWidget.setItem(2,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(3,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(4,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(5,l, QTableWidgetItem(str(0.00)))
             if (self.dlg.comboBox_27.currentText()==self.urbanchoices[5] ):
                 self.dlg.tableWidget.setItem(2,l, QTableWidgetItem(str((1.-iperv)*0.5)))
                 self.dlg.tableWidget.setItem(3,l, QTableWidgetItem(str((1.-iperv)*0.25)))
                 self.dlg.tableWidget.setItem(4,l, QTableWidgetItem(str((1.-iperv)*0.25)))
                 self.dlg.tableWidget.setItem(5,l, QTableWidgetItem(str(0.00)))
                 self.dlg.tableWidget.setItem(6,l, QTableWidgetItem(str(0.00)))
             if (self.dlg.comboBox_27.currentText()==self.urbanchoices[6] ):
                 self.dlg.tableWidget.setItem(2,l, QTableWidgetItem(str((1.-iperv)*0.2)))
                 self.dlg.tableWidget.setItem(3,l, QTableWidgetItem(str((1.-iperv)*0.2)))
                 self.dlg.tableWidget.setItem(4,l, QTableWidgetItem(str((1.-iperv)*0.2)))
                 self.dlg.tableWidget.setItem(5,l, QTableWidgetItem(str((1.-iperv)*0.2)))
                 self.dlg.tableWidget.setItem(6,l, QTableWidgetItem(str((1.-iperv)*0.2)))
             if (self.dlg.comboBox_28.currentText()==self.heightfr[0]):
                 self.dlg.tableWidget.setItem(8,l, QTableWidgetItem(str(0.5)))
                 self.dlg.tableWidget.setItem(12,l, QTableWidgetItem(str(0.3)))
                 self.dlg.tableWidget.setItem(14,l, QTableWidgetItem(str(1.0)))
             if (self.dlg.comboBox_28.currentText()==self.heightfr[1]):
                 self.dlg.tableWidget.setItem(8,l, QTableWidgetItem(str(4.0)))
                 self.dlg.tableWidget.setItem(12,l, QTableWidgetItem(str(1.0)))
                 self.dlg.tableWidget.setItem(14,l, QTableWidgetItem(str(5.0)))
             if (self.dlg.comboBox_28.currentText()==self.heightfr[2]):
                 self.dlg.tableWidget.setItem(8,l, QTableWidgetItem(str(7.5)))
                 self.dlg.tableWidget.setItem(12,l, QTableWidgetItem(str(1.8)))
                 self.dlg.tableWidget.setItem(14,l, QTableWidgetItem(str(10.0)))
             if (self.dlg.comboBox_28.currentText()==self.heightfr[3]):
                 self.dlg.tableWidget.setItem(8,l, QTableWidgetItem(str(12.5)))
                 self.dlg.tableWidget.setItem(12,l, QTableWidgetItem(str(1.8)))
                 self.dlg.tableWidget.setItem(14,l, QTableWidgetItem(str(15.0)))
             if (self.dlg.comboBox_28.currentText()==self.heightfr[4]):
                 self.dlg.tableWidget.setItem(8,l, QTableWidgetItem(str(17.5)))
                 self.dlg.tableWidget.setItem(12,l, QTableWidgetItem(str(2.0)))
                 self.dlg.tableWidget.setItem(14,l, QTableWidgetItem(str(20.0)))
             if (self.dlg.comboBox_28.currentText()==self.heightfr[5]):
                 self.dlg.tableWidget.setItem(8,l, QTableWidgetItem(str(30.0))) 
                 self.dlg.tableWidget.setItem(12,l, QTableWidgetItem(str(10)))
                 self.dlg.tableWidget.setItem(14,l, QTableWidgetItem(str(45.0)))
         else:
             iperv = float(self.dlg.tableWidget.item(0,l).text())+ float(self.dlg.tableWidget.item(1,l).text())+ float(self.dlg.tableWidget.item(2,l).text())+ float(self.dlg.tableWidget.item(5,l).text())+ float(self.dlg.tableWidget.item(6,l).text())
             if (self.dlg.comboBox_29.currentText()==self.treechoices[0] ):
                 self.dlg.tableWidget.setItem(4,l, QTableWidgetItem(str(1.-iperv)))
                 self.dlg.tableWidget.setItem(3,l, QTableWidgetItem(str(0.00)))
             if (self.dlg.comboBox_29.currentText()==self.treechoices[1] ):
                 self.dlg.tableWidget.setItem(3,l, QTableWidgetItem(str(1.-iperv)))
                 self.dlg.tableWidget.setItem(4,l, QTableWidgetItem(str(0.00)))
             if (self.dlg.comboBox_29.currentText()==self.treechoices[2] ):
                 self.dlg.tableWidget.setItem(3,l, QTableWidgetItem(str((1.-iperv)*0.5)))
                 self.dlg.tableWidget.setItem(4,l, QTableWidgetItem(str((1.-iperv)*0.5)))
             if (self.dlg.comboBox_29.currentText()==self.treechoices[3] ):
                 self.dlg.tableWidget.setItem(3,l, QTableWidgetItem(str((1.-iperv)*0.7)))
                 self.dlg.tableWidget.setItem(4,l, QTableWidgetItem(str((1.-iperv)*0.3)))   
             if (self.dlg.comboBox_29.currentText()==self.treechoices[4] ):
                 self.dlg.tableWidget.setItem(3,l, QTableWidgetItem(str((1.-iperv)*0.3)))
                 self.dlg.tableWidget.setItem(4,l, QTableWidgetItem(str((1.-iperv)*0.7)))
             if (self.dlg.comboBox_30.currentText()==self.heightfr[0]):
                 self.dlg.tableWidget.setItem(8,l, QTableWidgetItem(str(0.5)))
                 self.dlg.tableWidget.setItem(12,l, QTableWidgetItem(str(0.3)))
                 self.dlg.tableWidget.setItem(14,l, QTableWidgetItem(str(1.0)))
             if (self.dlg.comboBox_30.currentText()==self.heightfr[1]):
                 self.dlg.tableWidget.setItem(8,l, QTableWidgetItem(str(4.0)))
                 self.dlg.tableWidget.setItem(12,l, QTableWidgetItem(str(1.0)))
                 self.dlg.tableWidget.setItem(14,l, QTableWidgetItem(str(5.0)))
             if (self.dlg.comboBox_30.currentText()==self.heightfr[2]):
                 self.dlg.tableWidget.setItem(8,l, QTableWidgetItem(str(7.5)))
                 self.dlg.tableWidget.setItem(12,l, QTableWidgetItem(str(1.8)))
                 self.dlg.tableWidget.setItem(14,l, QTableWidgetItem(str(10.0)))
             if (self.dlg.comboBox_30.currentText()==self.heightfr[3]):
                 self.dlg.tableWidget.setItem(8,l, QTableWidgetItem(str(12.5)))
                 self.dlg.tableWidget.setItem(12,l, QTableWidgetItem(str(1.8)))
                 self.dlg.tableWidget.setItem(14,l, QTableWidgetItem(str(15.0)))
             if (self.dlg.comboBox_30.currentText()==self.heightfr[4]):
                 self.dlg.tableWidget.setItem(8,l, QTableWidgetItem(str(17.5)))
                 self.dlg.tableWidget.setItem(12,l, QTableWidgetItem(str(2.0)))
                 self.dlg.tableWidget.setItem(14,l, QTableWidgetItem(str(20.0)))
             if (self.dlg.comboBox_30.currentText()==self.heightfr[5]):
                 self.dlg.tableWidget.setItem(8,l, QTableWidgetItem(str(30.0))) 
                 self.dlg.tableWidget.setItem(12,l, QTableWidgetItem(str(10)))
                 self.dlg.tableWidget.setItem(14,l, QTableWidgetItem(str(45.0)))                
예제 #45
0
def make_widget(main, show=True):

    id = main.persistant['id']
    table = QTableWidget()
    table.controller = ROITableController(table, main)
    table.setGeometry(QRect(20, 33, 496, 296))
    table.setWindowTitle('ceilingfaan - ROI Table - Work in progress')
    analysis = s.query(Analysis).order_by(Analysis.date.desc()).all()
    table.setRowCount(len(analysis))
    table.setColumnCount(4)
    table.setHorizontalHeaderLabels(
        QString('CONTROL,DATE,MOUSE,FILENAME').split(','))

    current_analysis = None
    on_render = table.controller.on('render')
    on_import = table.controller.on('import')
    for nrow, entity in enumerate(analysis):
        if entity.id == id:
            print 'Found matching analysis data', id, 'at nrow:', nrow
            current_analysis = entity
            current_nrow = nrow
            continue

        for ncol, attr in enumerate('date mouse_id filename'.split()):
            field = getattr(entity, attr)
            item = QTableWidgetItem(str(field))
            item.setFlags(Qt.ItemIsEnabled)
            table.setItem(nrow, ncol + 1, item)

        render_btn = QPushButton('Render', checkable=True)
        render_btn.setStyleSheet('font-size: 9px; background-color: skyblue;')
        import_btn = QPushButton('Import')
        import_btn.setStyleSheet('font-size: 9px;')

        btn_layout = QHBoxLayout()
        btn_layout.setContentsMargins(5, 0, 5, 0)
        btn_layout.addWidget(render_btn)
        btn_layout.addWidget(import_btn)

        btn_widget = QWidget()
        btn_widget.nrow = nrow
        btn_widget.analysis_id = entity.id
        btn_widget.ext_roi_set = None
        btn_widget.setLayout(btn_layout)
        table.setCellWidget(nrow, 0, btn_widget)

        render_btn.clicked.connect(on_render)
        import_btn.clicked.connect(on_import)

    if current_analysis:
        table.removeRow(current_nrow)
        table.insertRow(0)
        item = QTableWidgetItem('Current Analysis')
        item.setFlags(Qt.ItemIsEnabled)
        item.setTextAlignment(Qt.AlignCenter)
        table.setItem(0, 0, item)
        for ncol, attr in enumerate('date mouse_id filename'.split()):
            field = getattr(current_analysis, attr)
            item = QTableWidgetItem(str(field))
            item.setFlags(Qt.ItemIsEnabled)
            table.setItem(0, ncol + 1, item)
        # debug.enter()

    table.setSelectionBehavior(QTableWidget.SelectRows)
    table.setSelectionMode(QTableWidget.NoSelection)
    table.resizeColumnsToContents()
    table.horizontalHeader().setStretchLastSection(True)

    if show: table.show()

    return table
예제 #46
0
 def populate_table(self, content_list, table_id):
     """
     populates the created table with the data
     :param table_id: int the id of the table to which write the data
     :param content_list: string data content
     :return: void
     """
     ref_table = self.tables[table_id]
     # handles the special case of the start/end list
     if table_id == 8:
         l = 1
         while l <= len(content_list) - 1:
             m = 0
             while m <= len(content_list[l]) - 1:
                 table_item = QTableWidgetItem(
                     str(content_list[l][m]).replace(",", ""), 0)
                 ref_table.setItem(l, m, table_item)
                 m += 1
             l += 1
         ref_table.removeRow(0)
     else:
         if table_id == 2 and self.include_footpath:
             self.validation_dk.ui.type3GroupBox.setTitle(
                 str(self.validation_dk.ui.type3GroupBox.title()) +
                 " (including footpaths)")
         # writes data to columns
         i = 1
         ordered_list = []
         while i <= len(content_list) - 1:
             item_list = str(content_list[i][0]).split('|')
             ordered_list.append(item_list)
             i += 1
         j = 0
         while j <= len(ordered_list) - 1:
             k = 0
             while k <= len(ordered_list[j]) - 1:
                 table_item = QTableWidgetItem(str(ordered_list[j][k]), 0)
                 ref_table.setItem(j, k, table_item)
                 k += 1
             j += 1
     # resize column widths to content
     ref_table.resizeColumnsToContents()
     # hide horizontal header
     ref_table.verticalHeader().hide()
     m = 0
     columns_sizes = 0
     while m <= self.columns_count - 1:
         header = ref_table.horizontalHeaderItem(m)
         column_size = ref_table.sizeHintForColumn(m)
         columns_sizes += column_size
         m += 1
     ref_table.horizontalHeader().setStretchLastSection(True)
     old_size = QSize()
     new_size = QSize()
     old_size.setWidth(ref_table.width())
     new_size.setWidth(columns_sizes)
     resize_event = QResizeEvent(new_size, old_size)
     ref_table.resizeEvent(resize_event)
     ref_table_selection_model = ref_table.selectionModel()
     ref_table.doubleClicked.connect(
         lambda: self.get_esu_or_usrn(ref_table_selection_model))
     ref_table.setToolTip(
         "Double click on a record to zoom to the feature.")
예제 #47
0
    def updatetable(self):
        lczboxes = [self.dlg.comboBox_3,self.dlg.comboBox_4,self.dlg.comboBox_5,
                    self.dlg.comboBox_6,self.dlg.comboBox_7,self.dlg.comboBox_8,self.dlg.comboBox_15,self.dlg.comboBox_16]
        lcfrboxes = [self.dlg.comboBox_9,self.dlg.comboBox_10,self.dlg.comboBox_11,
                     self.dlg.comboBox_12,self.dlg.comboBox_13,self.dlg.comboBox_14,self.dlg.comboBox_17,self.dlg.comboBox_18]
        heightboxes = [self.dlg.comboBox_19,self.dlg.comboBox_20,self.dlg.comboBox_21,
                       self.dlg.comboBox_22,self.dlg.comboBox_23,self.dlg.comboBox_24,self.dlg.comboBox_25,self.dlg.comboBox_26]
        for x in range(len(lczboxes)): 
            lcz = int(lczboxes[x].currentText())
            if lcz>10:
                iperv=float(self.dlg.tableWidget.item(0,lcz-91).text())+float(self.dlg.tableWidget.item(1,lcz-91).text())+float(self.dlg.tableWidget.item(2,lcz-91).text())+float(self.dlg.tableWidget.item(5,lcz-91).text())+float(self.dlg.tableWidget.item(6,lcz-91).text())
                if (lcfrboxes[x].currentText()==self.treechoices[0] ):
                    self.dlg.tableWidget.setItem(4,lcz-91, QTableWidgetItem(str(1.-iperv)))
                    self.dlg.tableWidget.setItem(3,lcz-91, QTableWidgetItem(str(0.00)))
                if (lcfrboxes[x].currentText()==self.treechoices[1] ):
                    self.dlg.tableWidget.setItem(3,lcz-91, QTableWidgetItem(str(1.-iperv)))
                    self.dlg.tableWidget.setItem(4,lcz-91, QTableWidgetItem(str(0.00)))
                if (lcfrboxes[x].currentText()==self.treechoices[2] ):
                    self.dlg.tableWidget.setItem(3,lcz-91, QTableWidgetItem(str((1.-iperv)*0.5)))
                    self.dlg.tableWidget.setItem(4,lcz-91, QTableWidgetItem(str((1.-iperv)*0.5)))
                if (lcfrboxes[x].currentText()==self.treechoices[3] ):
                    self.dlg.tableWidget.setItem(3,lcz-91, QTableWidgetItem(str((1.-iperv)*0.7)))
                    self.dlg.tableWidget.setItem(4,lcz-91, QTableWidgetItem(str((1.-iperv)*0.3)))   
                if (lcfrboxes[x].currentText()==self.treechoices[4] ):
                    self.dlg.tableWidget.setItem(3,lcz-91, QTableWidgetItem(str((1.-iperv)*0.3)))
                    self.dlg.tableWidget.setItem(4,lcz-91, QTableWidgetItem(str((1.-iperv)*0.7)))
                if (heightboxes[x].currentText()==self.heightfr[0]):
                    self.dlg.tableWidget.setItem(8,lcz-91, QTableWidgetItem(str(0.5)))
                    self.dlg.tableWidget.setItem(12,lcz-91, QTableWidgetItem(str(0.3)))
                    self.dlg.tableWidget.setItem(14,lcz-91, QTableWidgetItem(str(1.0)))
                if (heightboxes[x].currentText()==self.heightfr[1]):
                    self.dlg.tableWidget.setItem(8,lcz-91, QTableWidgetItem(str(4.0)))
                    self.dlg.tableWidget.setItem(12,lcz-91, QTableWidgetItem(str(1.0)))
                    self.dlg.tableWidget.setItem(14,lcz-91, QTableWidgetItem(str(5.0)))
                if (heightboxes[x].currentText()==self.heightfr[2]):
                    self.dlg.tableWidget.setItem(8,lcz-91, QTableWidgetItem(str(7.5)))
                    self.dlg.tableWidget.setItem(12,lcz-91, QTableWidgetItem(str(1.8)))
                    self.dlg.tableWidget.setItem(14,lcz-91, QTableWidgetItem(str(10.0)))
                if (heightboxes[x].currentText()==self.heightfr[3]):
                    self.dlg.tableWidget.setItem(8,lcz-91, QTableWidgetItem(str(12.5)))
                    self.dlg.tableWidget.setItem(12,lcz-91, QTableWidgetItem(str(1.8)))
                    self.dlg.tableWidget.setItem(14,lcz-91, QTableWidgetItem(str(15.0)))
                if (heightboxes[x].currentText()==self.heightfr[4]):
                    self.dlg.tableWidget.setItem(8,lcz-91, QTableWidgetItem(str(17.5)))
                    self.dlg.tableWidget.setItem(12,lcz-91, QTableWidgetItem(str(2.0)))
                    self.dlg.tableWidget.setItem(14,lcz-91, QTableWidgetItem(str(20.0)))
                if (heightboxes[x].currentText()==self.heightfr[5]):
                    self.dlg.tableWidget.setItem(8,lcz-91, QTableWidgetItem(str(30.0)))
                    self.dlg.tableWidget.setItem(12,lcz-91, QTableWidgetItem(str(10)))
                    self.dlg.tableWidget.setItem(14,lcz-91, QTableWidgetItem(str(45.0)))

            if lcz<=10:
                iperv=float(self.dlg.tableWidget.item(0,lcz-1).text())+float(self.dlg.tableWidget.item(1,lcz-1).text())
                if (lcfrboxes[x].currentText()==self.urbanchoices[0] ):
                    self.dlg.tableWidget.setItem(2,lcz-1, QTableWidgetItem(str(1.-iperv)))
                    self.dlg.tableWidget.setItem(3,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(4,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(5,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(6,lcz-1, QTableWidgetItem(str(0.00)))
                if (lcfrboxes[x].currentText()==self.urbanchoices[1] ):
                    self.dlg.tableWidget.setItem(3,lcz-1, QTableWidgetItem(str(1.-iperv)))
                    self.dlg.tableWidget.setItem(2,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(4,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(5,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(6,lcz-1, QTableWidgetItem(str(0.00)))
                if (lcfrboxes[x].currentText()==self.urbanchoices[2] ):
                    self.dlg.tableWidget.setItem(4,lcz-1, QTableWidgetItem(str(1.-iperv)))
                    self.dlg.tableWidget.setItem(2,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(3,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(5,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(6,lcz-1, QTableWidgetItem(str(0.00)))
                if (lcfrboxes[x].currentText()==self.urbanchoices[3] ):
                    self.dlg.tableWidget.setItem(5,lcz-1, QTableWidgetItem(str(1.-iperv)))
                    self.dlg.tableWidget.setItem(2,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(3,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(4,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(6,lcz-1, QTableWidgetItem(str(0.00)))
                if (lcfrboxes[x].currentText()==self.urbanchoices[4] ):
                    self.dlg.tableWidget.setItem(6,lcz-1, QTableWidgetItem(str(1.-iperv)))
                    self.dlg.tableWidget.setItem(2,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(3,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(4,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(5,lcz-1, QTableWidgetItem(str(0.00)))
                if (lcfrboxes[x].currentText()==self.urbanchoices[5] ):
                    self.dlg.tableWidget.setItem(2,lcz-1, QTableWidgetItem(str((1.-iperv)*0.5)))
                    self.dlg.tableWidget.setItem(3,lcz-1, QTableWidgetItem(str((1.-iperv)*0.25)))
                    self.dlg.tableWidget.setItem(4,lcz-1, QTableWidgetItem(str((1.-iperv)*0.25)))
                    self.dlg.tableWidget.setItem(5,lcz-1, QTableWidgetItem(str(0.00)))
                    self.dlg.tableWidget.setItem(6,lcz-1, QTableWidgetItem(str(0.00)))
                if (lcfrboxes[x].currentText()==self.urbanchoices[6] ):
                    self.dlg.tableWidget.setItem(2,lcz-1, QTableWidgetItem(str((1.-iperv)*0.2)))
                    self.dlg.tableWidget.setItem(3,lcz-1, QTableWidgetItem(str((1.-iperv)*0.2)))
                    self.dlg.tableWidget.setItem(4,lcz-1, QTableWidgetItem(str((1.-iperv)*0.2)))
                    self.dlg.tableWidget.setItem(5,lcz-1, QTableWidgetItem(str((1.-iperv)*0.2)))
                    self.dlg.tableWidget.setItem(6,lcz-1, QTableWidgetItem(str((1.-iperv)*0.2)))
                if (heightboxes[x].currentText()==self.heightfr[0]):
                    self.dlg.tableWidget.setItem(8,lcz-1, QTableWidgetItem(str(0.5)))
                    self.dlg.tableWidget.setItem(12,lcz-1, QTableWidgetItem(str(0.3)))
                    self.dlg.tableWidget.setItem(14,lcz-1, QTableWidgetItem(str(1.0)))
                if (heightboxes[x].currentText()==self.heightfr[1]):
                    self.dlg.tableWidget.setItem(8,lcz-1, QTableWidgetItem(str(4.0)))
                    self.dlg.tableWidget.setItem(12,lcz-1, QTableWidgetItem(str(1.0)))
                    self.dlg.tableWidget.setItem(14,lcz-1, QTableWidgetItem(str(5.0)))
                if (heightboxes[x].currentText()==self.heightfr[2]):
                    self.dlg.tableWidget.setItem(8,lcz-1, QTableWidgetItem(str(7.5)))
                    self.dlg.tableWidget.setItem(12,lcz-1, QTableWidgetItem(str(1.8)))
                    self.dlg.tableWidget.setItem(14,lcz-1, QTableWidgetItem(str(10.0)))
                if (heightboxes[x].currentText()==self.heightfr[3]):
                    self.dlg.tableWidget.setItem(8,lcz-1, QTableWidgetItem(str(12.5)))
                    self.dlg.tableWidget.setItem(12,lcz-1, QTableWidgetItem(str(1.8)))
                    self.dlg.tableWidget.setItem(14,lcz-1, QTableWidgetItem(str(15.0)))
                if (heightboxes[x].currentText()==self.heightfr[4]):
                    self.dlg.tableWidget.setItem(8,lcz-1, QTableWidgetItem(str(17.5)))
                    self.dlg.tableWidget.setItem(12,lcz-1, QTableWidgetItem(str(2.0)))
                    self.dlg.tableWidget.setItem(14,lcz-1, QTableWidgetItem(str(20.0)))
                if (heightboxes[x].currentText()==self.heightfr[5]):
                    self.dlg.tableWidget.setItem(8,lcz-1, QTableWidgetItem(str(30.0)))
                    self.dlg.tableWidget.setItem(12,lcz-1, QTableWidgetItem(str(10)))
                    self.dlg.tableWidget.setItem(14,lcz-1, QTableWidgetItem(str(45.0)))
예제 #48
0
    def remplir_tableau_recap(self):
        #        formations =
        #        print("test")
        self.tableWidget_recap.setRowCount(0)

        for formation in next(self.db_formation.recup_formation()):
            self.tableWidget_recap.insertRow(0)
            self.tableWidget_recap.setRowHeight(0, 300)

            #            print(formation.LIST_PARTICIPANTS)
            nom_formation = QTableWidgetItem(formation.NOM_FORMATION)
            #            print(formation.NOM_FORMATION)
            date_formation = QTableWidgetItem(str(formation.DATE_FORMATION))
            type_formation = QTableWidgetItem(formation.TYPE_FORMATION)

            domaine = formation.DOMAINE

            self.tableWidget_recap.setItem(0, 0, nom_formation)
            self.tableWidget_recap.setItem(0, 1, date_formation)
            self.tableWidget_recap.setItem(0, 2, type_formation)

            self.tableWidget_recap.setCellWidget(0, 3, QListWidget())
            try:
                self.tableWidget_recap.cellWidget(0, 3).addItems(domaine)
            except:
                pass

            self.tableWidget_recap.setCellWidget(0, 4, QTextEdit())
            try:
                self.tableWidget_recap.cellWidget(0, 4).setPlainText(
                    formation.PLAN)
            except:
                pass

            self.tableWidget_recap.setCellWidget(0, 5, QTableWidget())
            list_key = list(json.loads(formation.LIST_PARTICIPANTS[0]).keys())
            for ele in reversed(list_key):
                self.tableWidget_recap.cellWidget(0, 5).insertColumn(0)

#            print(list(json.loads(formation.LIST_PARTICIPANTS[0]).keys()))
            self.tableWidget_recap.cellWidget(
                0, 5).setHorizontalHeaderLabels(list_key)
            #            try:

            for participant in formation.LIST_PARTICIPANTS:
                #                print(participant)
                self.tableWidget_recap.cellWidget(0, 5).insertRow(0)

                self.tableWidget_recap.cellWidget(0, 5).setItem(
                    0, 0, QTableWidgetItem(json.loads(participant)["nom"]))
                self.tableWidget_recap.cellWidget(0, 5).setItem(
                    0, 1, QTableWidgetItem(json.loads(participant)["prenom"]))
                self.tableWidget_recap.cellWidget(0, 5).setItem(
                    0, 2, QTableWidgetItem(str(json.loads(participant)["id"])))
                self.tableWidget_recap.cellWidget(0, 5).setItem(
                    0, 3,
                    QTableWidgetItem(json.loads(participant)["resultat"]))
                self.tableWidget_recap.cellWidget(0, 5).setItem(
                    0, 4, QTableWidgetItem(json.loads(participant)["note"]))
                self.tableWidget_recap.cellWidget(0, 5).setItem(
                    0, 5,
                    QTableWidgetItem(json.loads(participant)["remarque"]))

#                print(json.loads(participant))

#                self.tableWidget_recap.cellWidget(0, 5).append(json.loads(participant).items())
#            except:
#                pass
#
#               self.tableWidget_recap.resizeRowsToContents()
        self.tableWidget_recap.resizeColumnsToContents()
        self.tableWidget_recap.verticalHeader().setStretchLastSection(True)

        self.tableWidget_recap.setColumnWidth(5, 625)
예제 #49
0
        def load_and_view_samples_from_train_and_dev(self, current, previous):
            print current.indexes()

            model_index = current.indexes()[0]

            morph_analyzes = unicode(
                self.listWidget_selected_file_contents.model().data(
                    model_index).toString()).strip().split(" ")
            # print morph_analyzes
            golden_morph_analysis = morph_analyzes[4]
            target = golden_morph_analysis[1:]

            other_morph_analyzes = morph_analyzes[5:]

            n_analyzes = len(other_morph_analyzes)

            self.label_3.setText("selected row id: %d" %
                                 int(morph_analyzes[0]))
            self.label_8.setText("%d %d" %
                                 (int(n_analyzes), int(morph_analyzes[0])))

            self.listWidget_selected_row.clear()
            self.listWidget_selected_row.addItems(
                QStringList(other_morph_analyzes))

            self.textEdit_golden_morph_analysis.setPlainText(
                golden_morph_analysis)

            # self.addRuleToTheListButton.clicked.connect(
            #     partial(self.save_to_file, n_analyzes=n_analyzes, entry_id=int(morph_analyzes[0])))

            # from functools import partial
            self.addRuleToTheListButton.clicked.connect(
                self.add_to_the_rule_dict)

            if len(other_morph_analyzes) == 1:
                self.textEdit_2.setPlainText(other_morph_analyzes[0])

            self.listWidget_selected_row.selectionModel(
            ).selectionChanged.connect(self.update_corrected_morph_analysis)

            print type(target)
            print target
            print target.encode("utf8")

            # target = target.replace("?", "\?")

            lines = subprocess.check_output(
                ("grep -F -m 50 %s ./dataset/errors.gungor.ner.train_and_dev" %
                 target).split(" "),
                shell=False)

            # print lines

            lines = [x.decode("utf8") for x in lines.split("\n")]

            print type(lines[0])
            print len(lines)

            self.tableWidget_samples_from_train_and_dev.clear()

            self.tableWidget_samples_from_train_and_dev.setColumnCount(
                n_analyzes + 1)
            self.tableWidget_samples_from_train_and_dev.setRowCount(
                len(lines) - 1)

            for row in range(
                    self.tableWidget_samples_from_train_and_dev.rowCount()):
                row_items = lines[row].split(" ")[2:]
                for column in range(
                        self.tableWidget_samples_from_train_and_dev.
                        columnCount()):
                    if column < len(row_items):
                        self.tableWidget_samples_from_train_and_dev.setItem(
                            row, column, QTableWidgetItem(row_items[column]))

            # self.tableWidget_samples_from_train_and_dev.resizeColumnToContents()
            for column in range(
                    self.tableWidget_samples_from_train_and_dev.columnCount()):
                self.tableWidget_samples_from_train_and_dev.resizeColumnToContents(
                    column)

            self.sort_and_save_button.clicked.connect(self.sort_and_save)
예제 #50
0
    def set_table_data(self):
        # Date of most recent session
        # Hack because the datetimes are coming back as aware but in UTC?
        # Are they being stored incorrectly in UTC?
        # Or is django just not retrieving them in the current timezone?
        target_date = runner.models.Session.objects.order_by(
            '-date_time_start')[0].date_time_start.astimezone(tz).date()
        self.target_date_display.setText(target_date.strftime('%Y-%m-%d'))

        # Only include sessions from at least this recent
        # This should be longer than the max vacation time
        recency_cutoff = target_date - datetime.timedelta(days=21)

        # Get all mice that are in training
        mice_qs = runner.models.Mouse.objects.filter(in_training=True)

        # Get previous session from each mouse
        previous_sessions = []
        previous_sessions_sort_keys = []
        new_mice = []
        for mouse in mice_qs.all():
            # Find previous sessions from this mouse from all boxes,
            # sorted by date and excluding ancient ones
            mouse_prev_sess_qs = runner.models.Session.objects.filter(
                mouse=mouse,
                date_time_start__date__gte=recency_cutoff,
            ).order_by('date_time_start')

            # Store the most recent, or if None, add to new_mice
            if mouse_prev_sess_qs.count() > 0:
                # The most recent
                sess = mouse_prev_sess_qs.last()

                # Skip if the last session was not in LOCALE_BOXES, that is,
                # if it was trained on some other setup
                if sess.box.name not in LOCALE_BOXES:
                    continue

                # Store sess
                previous_sessions.append(sess)

                # Store these sort keys to enable sorting
                # Index into LOCALE_BOXES
                previous_sessions_board_idx = LOCALE_BOXES.index(sess.box.name)

                # date time start
                dtstart = sess.date_time_start

                # sort keys
                previous_sessions_sort_keys.append(
                    (previous_sessions_board_idx, dtstart))
            else:
                new_mice.append(mouse)

        # Incantantion to sort previous_sessions by sort keys
        previous_sessions = [
            x for junk, x in sorted(
                zip(previous_sessions_sort_keys, previous_sessions))
        ]

        # Get the choices for box and board
        box_l = LOCALE_BOXES
        board_l = sorted(runner.models.Board.objects.all().values_list(
            'name', flat=True))

        # Get box arduinos and cameras for polling
        self.relevant_box_names = []
        self.relevant_box_arduinos = []
        self.relevant_box_cameras = []
        for box_name in box_l:
            box = runner.models.Box.objects.filter(name=box_name).first()
            self.relevant_box_names.append(box_name)
            self.relevant_box_arduinos.append(box.serial_port)
            self.relevant_box_cameras.append(box.video_device)

        # Set every row with the same widgets
        # 0 - Mouse, read only
        # 1 - Weight, text box
        # 2 - Box, combo box
        # 3 - Board, combo box
        # 4 - Previous pipe, read only
        # 5 - Previous perf, read only
        # 6 - Start, button
        # 7 - Performance, read only
        # 8 - Pipe stop, read only

        self.daily_plan_table.setRowCount(len(previous_sessions))
        for nrow, session in enumerate(previous_sessions):
            # Set the row height
            self.daily_plan_table.setRowHeight(nrow, ROW_HEIGHT)

            # Mouse name, read only
            item = QTableWidgetItem(session.mouse.name)
            item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
            self.daily_plan_table.setItem(nrow, 0, item)

            # Weight, text box
            item = QTableWidgetItem(str(session.user_data_weight))
            self.daily_plan_table.setItem(nrow, 1, item)

            # Box, combo box
            qcb = create_combo_box(box_l, choice=session.box.name)
            self.daily_plan_table.setCellWidget(nrow, 2, qcb)

            # Board, combo box
            qcb = create_combo_box(board_l, choice=session.board.name)
            self.daily_plan_table.setCellWidget(nrow, 3, qcb)

            # Previous pipe, read only
            try:
                text = '%0.2f' % session.user_data_water_pipe_position_stop
            except TypeError:
                text = ''
            item = QTableWidgetItem(text)
            item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
            self.daily_plan_table.setItem(nrow, 4, item)

            # Previous perf, read only
            try:
                text = '%0.f; %0.f' % (
                    100 * session.user_data_left_perf,
                    100 * session.user_data_right_perf,
                )
            except TypeError:
                text = ''
            item = QTableWidgetItem(text)
            item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
            self.daily_plan_table.setItem(nrow, 5, item)

            # Start, button
            qb = QPushButton('Start')
            #~ qb.setCheckable(True)
            qb.clicked.connect(functools.partial(self.start_session2, qb))
            self.daily_plan_table.setCellWidget(nrow, 6, qb)

            # New perf, read only
            item = QTableWidgetItem('-')
            item.setFlags(item.flags() ^ QtCore.Qt.ItemIsEditable)
            self.daily_plan_table.setItem(nrow, 7, item)

            # New pipe, text box
            item = QTableWidgetItem('-')
            self.daily_plan_table.setItem(nrow, 8, item)
예제 #51
0
	def _actualizarDatosDinamicos(self):
		for i in range(len(self.contenedor)):
			self.tablaDatos.setItem(i, 3, QTableWidgetItem(str(self.contenedor[i].prioridad)))
			self.tablaDatos.setItem(i, 4, QTableWidgetItem(str(self.contenedor[i].edad)))
예제 #52
0
                          "programming, with high-quality technical articles "
                          "written by Qt experts.")
    textWindow = mdiArea.addSubWindow(textEdit)
    textWindow.setWindowTitle("A Text Editor")

    label = QLabel()
    label.setPixmap(QPixmap("../../images/qt-logo.png"))
    labelWindow = mdiArea.addSubWindow(label)
    labelWindow.setWindowTitle("A Label")

    items = (("Henry", 23), ("Bill", 56), ("Susan", 19), ("Jane", 47))
    table = QTableWidget(len(items), 2)

    for i in range(len(items)):
        name, age = items[i]
        item = QTableWidgetItem(name)
        table.setItem(i, 0, item)
        item = QTableWidgetItem(str(age))
        table.setItem(i, 1, item)

    tableWindow = mdiArea.addSubWindow(table)
    tableWindow.setWindowTitle("A Table Widget")

    mdiArea.show()

    changer = Changer(mdiArea)
    button = QPushButton("Cascade")
    button.connect(button, SIGNAL("clicked()"), changer.change)
    button.show()
    sys.exit(app.exec_())
예제 #53
0
    def _populateTable(self, features, labels, *args):
        self.progressBar.hide()
        self.computeButton.setEnabled(True)
                
        for time, feature in features.iteritems():
            # Insert row
            rowNum = self.table.rowCount()
            self.table.insertRow(self.table.rowCount())
            
            # Get max and min object areas
            areas = feature['Count']#objectFeatures['Standard Object Features']['Count']
            maxObjArea = numpy.max(areas[numpy.nonzero(areas)])
            minObjArea = numpy.min(areas[numpy.nonzero(areas)])
            
            # Get number of labeled objects
            labelNum = numpy.count_nonzero(labels[time])
            
            # Load fram number
            item = QTableWidgetItem(str(time))
            item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
            self.table.setItem(rowNum, 0, item) 

            # Load max object areas
            item = QTableWidgetItemWithFloatSorting(str("{: .02f}".format(maxObjArea)))
            item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
            self.table.setItem(rowNum, 1, item)
                
            # Load min object areas
            item = QTableWidgetItemWithFloatSorting(str("{: .02f}".format(minObjArea)))
            item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
            self.table.setItem(rowNum, 2, item)
            
            # Load label numbers
            item = QTableWidgetItemWithFloatSorting(str("{: .01f}".format(labelNum)))
            item.setFlags( Qt.ItemIsSelectable |  Qt.ItemIsEnabled )
            self.table.setItem(rowNum, 3, item)
        
        # Resize column size to fit dialog size
        self.table.horizontalHeader().setResizeMode(QHeaderView.Stretch)   
        
        # Sort by max object area
        self.table.setSortingEnabled(True)                         
        self.table.sortByColumn(1) 
예제 #54
0
    def restoreSettings(self):
        settings = QSettings()
        self.spinBox.setValue(
            settings.value("pythonConsole/fontsize", 10, type=int))
        self.spinBoxEditor.setValue(
            settings.value("pythonConsole/fontsizeEditor", 10, type=int))
        self.fontComboBox.setCurrentFont(
            QFont(settings.value("pythonConsole/fontfamilytext", "Monospace")))
        self.fontComboBoxEditor.setCurrentFont(
            QFont(
                settings.value("pythonConsole/fontfamilytextEditor",
                               "Monospace")))
        self.preloadAPI.setChecked(
            settings.value("pythonConsole/preloadAPI", True, type=bool))
        self.lineEdit.setText(
            settings.value("pythonConsole/preparedAPIFile", "", type=str))
        itemTable = settings.value("pythonConsole/userAPI", [])
        if itemTable:
            self.tableWidget.setRowCount(0)
            for i in range(len(itemTable)):
                self.tableWidget.insertRow(i)
                self.tableWidget.setColumnCount(2)
                pathSplit = itemTable[i].split("/")
                apiName = pathSplit[-1][0:-4]
                self.tableWidget.setItem(i, 0, QTableWidgetItem(apiName))
                self.tableWidget.setItem(i, 1, QTableWidgetItem(itemTable[i]))
        self.autoSaveScript.setChecked(
            settings.value("pythonConsole/autoSaveScript", False, type=bool))

        self.autoCompThreshold.setValue(
            settings.value("pythonConsole/autoCompThreshold", 2, type=int))
        self.autoCompThresholdEditor.setValue(
            settings.value("pythonConsole/autoCompThresholdEditor",
                           2,
                           type=int))
        self.groupBoxAutoCompletionEditor.setChecked(
            settings.value("pythonConsole/autoCompleteEnabledEditor",
                           True,
                           type=bool))
        self.groupBoxAutoCompletion.setChecked(
            settings.value("pythonConsole/autoCompleteEnabled",
                           True,
                           type=bool))

        self.enableObjectInspector.setChecked(
            settings.value("pythonConsole/enableObjectInsp", False, type=bool))
        self.autoCloseBracketEditor.setChecked(
            settings.value("pythonConsole/autoCloseBracketEditor",
                           False,
                           type=bool))
        self.autoCloseBracket.setChecked(
            settings.value("pythonConsole/autoCloseBracket", False, type=bool))
        self.autoInsertionImportEditor.setChecked(
            settings.value("pythonConsole/autoInsertionImportEditor",
                           True,
                           type=bool))
        self.autoInsertionImport.setChecked(
            settings.value("pythonConsole/autoInsertionImport",
                           True,
                           type=bool))

        if settings.value("pythonConsole/autoCompleteSource") == 'fromDoc':
            self.autoCompFromDoc.setChecked(True)
        elif settings.value("pythonConsole/autoCompleteSource") == 'fromAPI':
            self.autoCompFromAPI.setChecked(True)
        elif settings.value(
                "pythonConsole/autoCompleteSource") == 'fromDocAPI':
            self.autoCompFromDocAPI.setChecked(True)

        if settings.value(
                "pythonConsole/autoCompleteSourceEditor") == 'fromDoc':
            self.autoCompFromDocEditor.setChecked(True)
        elif settings.value(
                "pythonConsole/autoCompleteSourceEditor") == 'fromAPI':
            self.autoCompFromAPIEditor.setChecked(True)
        elif settings.value(
                "pythonConsole/autoCompleteSourceEditor") == 'fromDocAPI':
            self.autoCompFromDocAPIEditor.setChecked(True)

        ## Setting font lexer color
        self.defaultFontColor.setColor(
            QColor(
                settings.value("pythonConsole/defaultFontColor",
                               QColor(Qt.black))))
        self.defaultFontColorEditor.setColor(
            QColor(
                settings.value("pythonConsole/defaultFontColorEditor",
                               QColor(Qt.black))))
        self.keywordFontColor.setColor(
            QColor(
                settings.value("pythonConsole/keywordFontColor",
                               QColor(Qt.darkGreen))))
        self.keywordFontColorEditor.setColor(
            QColor(
                settings.value("pythonConsole/keywordFontColorEditor",
                               QColor(Qt.darkGreen))))
        self.classFontColor.setColor(
            QColor(
                settings.value("pythonConsole/classFontColor",
                               QColor(Qt.blue))))
        self.classFontColorEditor.setColor(
            QColor(
                settings.value("pythonConsole/classFontColorEditor",
                               QColor(Qt.blue))))
        self.methodFontColor.setColor(
            QColor(
                settings.value("pythonConsole/methodFontColor",
                               QColor(Qt.darkGray))))
        self.methodFontColorEditor.setColor(
            QColor(
                settings.value("pythonConsole/methodFontColorEditor",
                               QColor(Qt.darkGray))))
        self.decorFontColor.setColor(
            QColor(
                settings.value("pythonConsole/decorFontColor",
                               QColor(Qt.darkBlue))))
        self.decorFontColorEditor.setColor(
            QColor(
                settings.value("pythonConsole/decorFontColorEditor",
                               QColor(Qt.darkBlue))))
        self.commentFontColor.setColor(
            QColor(
                settings.value("pythonConsole/commentFontColor",
                               QColor(Qt.gray))))
        self.commentFontColorEditor.setColor(
            QColor(
                settings.value("pythonConsole/commentFontColorEditor",
                               QColor(Qt.gray))))
        self.commentBlockFontColor.setColor(
            QColor(
                settings.value("pythonConsole/commentBlockFontColor",
                               QColor(Qt.gray))))
        self.commentBlockFontColorEditor.setColor(
            QColor(
                settings.value("pythonConsole/commentBlockFontColorEditor",
                               QColor(Qt.gray))))
        self.paperBackgroundColor.setColor(
            QColor(
                settings.value("pythonConsole/paperBackgroundColor",
                               QColor(Qt.white))))
        self.paperBackgroundColorEditor.setColor(
            QColor(
                settings.value("pythonConsole/paperBackgroundColorEditor",
                               QColor(Qt.white))))
        self.caretLineColor.setColor(
            QColor(
                settings.value("pythonConsole/caretLineColor",
                               QColor("#fcf3ed"))))
        self.caretLineColorEditor.setColor(
            QColor(
                settings.value("pythonConsole/caretLineColorEditor",
                               QColor("#fcf3ed"))))
        self.cursorColor.setColor(
            QColor(
                settings.value("pythonConsole/cursorColor", QColor(Qt.black))))
        self.cursorColorEditor.setColor(
            QColor(
                settings.value("pythonConsole/cursorColorEditor",
                               QColor(Qt.black))))
        self.stderrFontColor.setColor(
            QColor(
                settings.value("pythonConsole/stderrFontColor",
                               QColor(Qt.red))))

        self.singleQuoteFontColor.setColor(
            settings.value("pythonConsole/singleQuoteFontColor",
                           QColor(Qt.blue)))
        self.singleQuoteFontColorEditor.setColor(
            settings.value("pythonConsole/singleQuoteFontColorEditor",
                           QColor(Qt.blue)))
        self.doubleQuoteFontColor.setColor(
            settings.value("pythonConsole/doubleQuoteFontColor",
                           QColor(Qt.blue)))
        self.doubleQuoteFontColorEditor.setColor(
            settings.value("pythonConsole/doubleQuoteFontColorEditor",
                           QColor(Qt.blue)))
        self.tripleSingleQuoteFontColor.setColor(
            settings.value("pythonConsole/tripleSingleQuoteFontColor",
                           QColor(Qt.blue)))
        self.tripleSingleQuoteFontColorEditor.setColor(
            settings.value("pythonConsole/tripleSingleQuoteFontColorEditor",
                           QColor(Qt.blue)))
        self.tripleDoubleQuoteFontColor.setColor(
            settings.value("pythonConsole/tripleDoubleQuoteFontColor",
                           QColor(Qt.blue)))
        self.tripleDoubleQuoteFontColorEditor.setColor(
            settings.value("pythonConsole/tripleDoubleQuoteFontColorEditor",
                           QColor(Qt.blue)))
예제 #55
0
 def __init__(self, text, sort_key):
     QTableWidgetItem.__init__(self, text, QTableWidgetItem.UserType)
     self.sort_key = sort_key
예제 #56
0
    def __insertRow(self, repoName, repoAddress):
        currentRow = self.settings.repoListView.rowCount()
        self.settings.repoListView.insertRow(currentRow)
        checkbox = QCheckBox(self.settings.repoListView)
        self.connect(checkbox, SIGNAL("toggled(bool)"), self.markChanged)
        self.settings.repoListView.setCellWidget(currentRow, 0, checkbox)
        self.settings.repoListView.cellWidget(currentRow, 0).setChecked(self.iface.isRepoActive(repoName))

        repoNameItem = QTableWidgetItem()
        repoNameItem.setText(repoName)
        repoNameItem.setTextAlignment(Qt.AlignLeft|Qt.AlignVCenter)
        self.settings.repoListView.setItem(currentRow, 1, repoNameItem)

        repoAddressItem = QTableWidgetItem()
        repoAddressItem.setText(repoAddress)
        repoAddressItem.setTextAlignment(Qt.AlignLeft|Qt.AlignVCenter)
        self.settings.repoListView.setItem(currentRow, 2, repoAddressItem)
예제 #57
0
    def filltWTasksView(self, tasks):

        rowCount = len(tasks)
        self.ui.tWTasks.setRowCount(rowCount)
        row = 0
        for taskname, task in tasks.items():
            item = QTableWidgetItem()
            item.setText(task.taskName)
            self.ui.tWTasks.setItem(row, 0, item)

            item = QtGui.QTableWidgetItem()
            item.setText(unicode(task.storeName))
            self.ui.tWTasks.setItem(row, 1, item)

            item = QtGui.QTableWidgetItem()
            item.setText(task.reservType)
            self.ui.tWTasks.setItem(row, 2, item)

            item = QtGui.QTableWidgetItem()
            item.setText(task.proxyServer)
            self.ui.tWTasks.setItem(row, 3, item)

            item = QtGui.QTableWidgetItem()
            item.setText(task.proxyPort)
            self.ui.tWTasks.setItem(row, 4, item)
            row += 1
예제 #58
0
    def initialize(self, *args, **kwargs):
        " Init Main Class "
        super(Main, self).initialize(*args, **kwargs)
        self.scriptPath, self.scriptArgs = "", []
        self.profilerPath, self.tempPath = profilerPath, tempPath
        self.output = " ERROR: FAIL: No output ! "

        self.process = QProcess()
        self.process.finished.connect(self.on_process_finished)
        self.process.error.connect(self.on_process_error)

        self.tabWidget, self.stat = QTabWidget(), QWidget()
        self.tabWidget.tabCloseRequested.connect(
            lambda: self.tabWidget.setTabPosition(1) if self.tabWidget.
            tabPosition() == 0 else self.tabWidget.setTabPosition(0))
        self.tabWidget.setStyleSheet('QTabBar{font-weight:bold;}')
        self.tabWidget.setMovable(True)
        self.tabWidget.setTabsClosable(True)
        self.vboxlayout1 = QVBoxLayout(self.stat)
        self.hboxlayout1 = QHBoxLayout()
        self.filterTableLabel = QLabel("<b>Type to Search : </b>", self.stat)
        self.hboxlayout1.addWidget(self.filterTableLabel)
        self.filterTableLineEdit = QLineEdit(self.stat)
        self.filterTableLineEdit.setPlaceholderText(' Type to Search . . . ')
        self.hboxlayout1.addWidget(self.filterTableLineEdit)
        self.filterHintTableLabel = QLabel(" ? ", self.stat)
        self.hboxlayout1.addWidget(self.filterHintTableLabel)
        self.vboxlayout1.addLayout(self.hboxlayout1)
        self.tableWidget = QTableWidget(self.stat)
        self.tableWidget.setAlternatingRowColors(True)
        self.tableWidget.setColumnCount(8)
        self.tableWidget.setRowCount(2)
        item = QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(1, item)
        item = QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(2, item)
        item = QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(3, item)
        item = QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(4, item)
        item = QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(5, item)
        item = QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(6, item)
        item = QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(7, item)
        self.tableWidget.itemDoubleClicked.connect(
            self.on_tableWidget_itemDoubleClicked)
        self.vboxlayout1.addWidget(self.tableWidget)
        self.tabWidget.addTab(self.stat, " ? ")

        self.source = QWidget()
        self.gridlayout = QGridLayout(self.source)
        self.scintillaWarningLabel = QLabel(
            "QScintilla is not installed!. Falling back to basic text edit!.",
            self.source)
        self.gridlayout.addWidget(self.scintillaWarningLabel, 1, 0, 1, 2)
        self.sourceTreeWidget = QTreeWidget(self.source)
        self.sourceTreeWidget.setAlternatingRowColors(True)
        self.sourceTreeWidget.itemActivated.connect(
            self.on_sourceTreeWidget_itemActivated)
        self.sourceTreeWidget.itemClicked.connect(
            self.on_sourceTreeWidget_itemClicked)
        self.sourceTreeWidget.itemDoubleClicked.connect(
            self.on_sourceTreeWidget_itemClicked)

        self.gridlayout.addWidget(self.sourceTreeWidget, 0, 0, 1, 1)
        self.sourceTextEdit = QTextEdit(self.source)
        self.sourceTextEdit.setReadOnly(True)
        self.gridlayout.addWidget(self.sourceTextEdit, 0, 1, 1, 1)
        self.tabWidget.addTab(self.source, " ? ")

        self.result = QWidget()
        self.vlayout = QVBoxLayout(self.result)
        self.globalStatGroupBox = QGroupBox(self.result)
        self.hboxlayout = QHBoxLayout(self.globalStatGroupBox)
        self.totalTimeLcdNumber = QLCDNumber(self.globalStatGroupBox)
        self.totalTimeLcdNumber.setSegmentStyle(QLCDNumber.Filled)
        self.totalTimeLcdNumber.setNumDigits(7)
        self.totalTimeLcdNumber.display(1000000)
        self.totalTimeLcdNumber.setFrameShape(QFrame.StyledPanel)
        self.totalTimeLcdNumber.setSizePolicy(QSizePolicy.Expanding,
                                              QSizePolicy.Expanding)
        self.hboxlayout.addWidget(self.totalTimeLcdNumber)
        self.tTimeLabel = QLabel("<b>Total Time (Sec)</b>",
                                 self.globalStatGroupBox)
        self.tTimeLabel.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.hboxlayout.addWidget(self.tTimeLabel)
        self.numCallLcdNumber = QLCDNumber(self.globalStatGroupBox)
        self.numCallLcdNumber.setNumDigits(7)
        self.numCallLcdNumber.display(1000000)
        self.numCallLcdNumber.setSegmentStyle(QLCDNumber.Filled)
        self.numCallLcdNumber.setFrameShape(QFrame.StyledPanel)
        self.numCallLcdNumber.setSizePolicy(QSizePolicy.Expanding,
                                            QSizePolicy.Expanding)
        self.hboxlayout.addWidget(self.numCallLcdNumber)
        self.numCallLabel = QLabel("<b>Number of calls</b>",
                                   self.globalStatGroupBox)
        self.numCallLabel.setSizePolicy(QSizePolicy.Minimum,
                                        QSizePolicy.Minimum)
        self.hboxlayout.addWidget(self.numCallLabel)
        self.primCallLcdNumber = QLCDNumber(self.globalStatGroupBox)
        self.primCallLcdNumber.setSegmentStyle(QLCDNumber.Filled)
        self.primCallLcdNumber.setFrameShape(QFrame.StyledPanel)
        self.primCallLcdNumber.setNumDigits(7)
        self.primCallLcdNumber.display(1000000)
        self.primCallLcdNumber.setSizePolicy(QSizePolicy.Expanding,
                                             QSizePolicy.Expanding)
        self.hboxlayout.addWidget(self.primCallLcdNumber)
        self.primCallLabel = QLabel("<b>Primitive calls (%)</b>",
                                    self.globalStatGroupBox)
        self.primCallLabel.setSizePolicy(QSizePolicy.Minimum,
                                         QSizePolicy.Minimum)
        self.hboxlayout.addWidget(self.primCallLabel)
        self.vlayout.addWidget(self.globalStatGroupBox)
        try:
            from PyKDE4.kdeui import KRatingWidget
            self.rating = KRatingWidget(self.globalStatGroupBox)
            self.rating.setToolTip('Profiling Performance Rating')
        except ImportError:
            pass
        self.tabWidget.addTab(self.result, " Get Results ! ")

        self.resgraph = QWidget()
        self.vlayout2 = QVBoxLayout(self.result)
        self.graphz = QGroupBox(self.resgraph)
        self.hboxlayout2 = QHBoxLayout(self.graphz)
        try:
            from PyKDE4.kdeui import KLed
            KLed(self.graphz)
        except ImportError:
            pass
        self.hboxlayout2.addWidget(
            QLabel('''
            Work in Progress  :)  Not Ready Yet'''))
        self.vlayout2.addWidget(self.graphz)
        self.tabWidget.addTab(self.resgraph, " Graphs and Charts ")

        self.pathz = QWidget()
        self.vlayout3 = QVBoxLayout(self.pathz)
        self.patz = QGroupBox(self.pathz)
        self.hboxlayout3 = QVBoxLayout(self.patz)
        self.profilepath = QLineEdit(profilerPath)
        self.getprofile = QPushButton(QIcon.fromTheme("document-open"), 'Open')
        self.getprofile.setToolTip(
            'Dont touch if you dont know what are doing')
        self.getprofile.clicked.connect(lambda: self.profilepath.setText(
            str(
                QFileDialog.getOpenFileName(
                    self.patz, ' Open the profile.py file ',
                    path.expanduser("~"), ';;(profile.py)'))))
        self.hboxlayout3.addWidget(
            QLabel(
                '<center><b>Profile.py Python Library Full Path:</b></center>')
        )
        self.hboxlayout3.addWidget(self.profilepath)
        self.hboxlayout3.addWidget(self.getprofile)

        self.argGroupBox = QGroupBox(self.pathz)
        self.hbxlayout = QHBoxLayout(self.argGroupBox)
        self.argLineEdit = QLineEdit(self.argGroupBox)
        self.argLineEdit.setToolTip(
            'Not touch if you dont know what are doing')
        self.argLineEdit.setPlaceholderText(
            'Dont touch if you dont know what are doing')
        self.hbxlayout.addWidget(
            QLabel('<b>Additional Profile Arguments:</b>'))
        self.hbxlayout.addWidget(self.argLineEdit)
        self.hboxlayout3.addWidget(self.argGroupBox)

        self.vlayout3.addWidget(self.patz)
        self.tabWidget.addTab(self.pathz, " Paths and Configs ")

        self.outp = QWidget()
        self.vlayout4 = QVBoxLayout(self.outp)
        self.outgro = QGroupBox(self.outp)
        self.outgro.setTitle(" MultiProcessing Output Logs ")
        self.hboxlayout4 = QVBoxLayout(self.outgro)
        self.outputlog = QTextEdit()
        self.outputlog.setText('''
        I do not fear computers, I fear the lack of them.   -Isaac Asimov ''')
        self.hboxlayout4.addWidget(self.outputlog)
        self.vlayout4.addWidget(self.outgro)
        self.tabWidget.addTab(self.outp, " Logs ")

        self.actionNew_profiling = QAction(QIcon.fromTheme("document-new"),
                                           'New Profiling', self)
        self.actionLoad_profile = QAction(QIcon.fromTheme("document-open"),
                                          'Open Profiling', self)
        self.actionClean = QAction(QIcon.fromTheme("edit-clear"), 'Clean',
                                   self)
        self.actionClean.triggered.connect(lambda: self.clearContent)
        self.actionAbout = QAction(QIcon.fromTheme("help-about"), 'About',
                                   self)
        self.actionAbout.triggered.connect(lambda: QMessageBox.about(
            self.dock, __doc__, ', '.join(
                (__doc__, __license__, __author__, __email__))))
        self.actionSave_profile = QAction(QIcon.fromTheme("document-save"),
                                          'Save Profiling', self)
        self.actionManual = QAction(QIcon.fromTheme("help-contents"), 'Help',
                                    self)
        self.actionManual.triggered.connect(lambda: open_new_tab(
            'http://docs.python.org/library/profile.html'))

        self.tabWidget.setCurrentIndex(2)

        self.globalStatGroupBox.setTitle("Global Statistics")
        item = self.tableWidget.horizontalHeaderItem(0)
        item.setText("Number of Calls")
        item = self.tableWidget.horizontalHeaderItem(1)
        item.setText("Total Time")
        item = self.tableWidget.horizontalHeaderItem(2)
        item.setText("Per Call")
        item = self.tableWidget.horizontalHeaderItem(3)
        item.setText("Cumulative Time")
        item = self.tableWidget.horizontalHeaderItem(4)
        item.setText("Per Call")
        item = self.tableWidget.horizontalHeaderItem(5)
        item.setText("Filename")
        item = self.tableWidget.horizontalHeaderItem(6)
        item.setText("Line")
        item = self.tableWidget.horizontalHeaderItem(7)
        item.setText("Function")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.stat),
                                  "Statistics per Function")

        self.sourceTreeWidget.headerItem().setText(0, "Source files")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.source),
                                  "Sources Navigator")
        #######################################################################

        self.scrollable, self.dock = QScrollArea(), QDockWidget()
        self.scrollable.setWidgetResizable(True)
        self.scrollable.setWidget(self.tabWidget)
        self.dock.setWindowTitle(__doc__)
        self.dock.setStyleSheet('QDockWidget::title{text-align: center;}')
        self.dock.setWidget(self.scrollable)
        QToolBar(self.dock).addActions(
            (self.actionNew_profiling, self.actionClean,
             self.actionSave_profile, self.actionLoad_profile,
             self.actionManual, self.actionAbout))

        self.actionNew_profiling.triggered.connect(
            self.on_actionNew_profiling_triggered)
        self.actionLoad_profile.triggered.connect(
            self.on_actionLoad_profile_triggered)
        self.actionSave_profile.triggered.connect(
            self.on_actionSave_profile_triggered)

        self.locator.get_service('misc').add_widget(
            self.dock, QIcon.fromTheme("document-open-recent"), __doc__)

        if QSCI:
            # Scintilla source editor management
            self.scintillaWarningLabel.setText(' QScintilla is Ready ! ')
            layout = self.source.layout()
            layout.removeWidget(self.sourceTextEdit)
            self.sourceTextEdit = Qsci.QsciScintilla(self.source)
            layout.addWidget(self.sourceTextEdit, 0, 1)
            doc = self.sourceTextEdit
            doc.setLexer(Qsci.QsciLexerPython(self.sourceTextEdit))
            doc.setReadOnly(True)
            doc.setEdgeMode(Qsci.QsciScintilla.EdgeLine)
            doc.setEdgeColumn(80)
            doc.setEdgeColor(QColor("#FF0000"))
            doc.setFolding(Qsci.QsciScintilla.BoxedTreeFoldStyle)
            doc.setBraceMatching(Qsci.QsciScintilla.SloppyBraceMatch)
            doc.setCaretLineVisible(True)
            doc.setMarginLineNumbers(1, True)
            doc.setMarginWidth(1, 25)
            doc.setTabWidth(4)
            doc.setEolMode(Qsci.QsciScintilla.EolUnix)
            self.marker = {}
            for color in COLORS:
                mnr = doc.markerDefine(Qsci.QsciScintilla.Background)
                doc.setMarkerBackgroundColor(color, mnr)
                self.marker[color] = mnr
        self.currentSourcePath = None

        # Connect table and tree filter edit signal to unique slot
        self.filterTableLineEdit.textEdited.connect(
            self.on_filterLineEdit_textEdited)

        # Timer to display filter hint message
        self.filterHintTimer = QTimer(self)
        self.filterHintTimer.setSingleShot(True)
        self.filterHintTimer.timeout.connect(self.on_filterHintTimer_timeout)

        # Timer to start search
        self.filterSearchTimer = QTimer(self)
        self.filterSearchTimer.setSingleShot(True)
        self.filterSearchTimer.timeout.connect(
            self.on_filterSearchTimer_timeout)

        self.tabLoaded = {}
        for i in range(10):
            self.tabLoaded[i] = False
        self.backgroundTreeMatchedItems = {}
        self.resizeWidgetToContent(self.tableWidget)
예제 #59
0
    def populateFieldTable(self):
        if self.collectedDataDict:
            importingFields = self.collectedDataDict[0].keys()
            self.fieldTable.clear()
            self.fieldTable.setRowCount(len(importingFields))
            predefinedFields = ['EOMETRY', 'ODKUUID']
            for row, field in enumerate(importingFields):
                enabledItem = QTableWidgetItem()
                enabledItem.setFlags(enabledItem.flags()
                                     | Qt.ItemIsUserCheckable)
                enabledItem.setText("")
                self.fieldTable.setItem(row, 0, enabledItem)
                ODKfieldItem = QTableWidgetItem()
                ODKfieldItem.setText(field)
                self.fieldTable.setItem(row, 1, ODKfieldItem)
                self.fieldTable.setRowHeight(row, 30)
                QGISfieldItem = QTableWidgetItem()

                # try to guess field mapping
                QGISfieldItem.setText("")
                enabledItem.setCheckState(Qt.Unchecked)
                for fieldOrigin, FieldDest in self.fieldMapping.iteritems():
                    if fieldOrigin in slugify(field):
                        QGISfieldItem.setText(FieldDest)
                        enabledItem.setCheckState(Qt.Checked)
                        break
                '''
                if slugify(field) in self.fieldMapping:
                    QGISfieldItem.setText(self.fieldMapping[slugify(field)])
                    enabledItem.setCheckState(Qt.Checked)
                else:
                    QGISfieldItem.setText("")
                    enabledItem.setCheckState(Qt.Unchecked)
                '''

                self.fieldTable.setItem(row, 2, QGISfieldItem)
                if field[
                        -7:] in predefinedFields:  #prevent predefined fields user editing
                    if field[-7:] == 'ODKUUID':
                        ODKfieldItem.setText('ODKUUID')
                        QGISfieldItem.setText('ODKUUID')
                    elif field[-7:] == 'EOMETRY':
                        ODKfieldItem.setText('GEOMETRY')
                        QGISfieldItem.setText('GEOMETRY')
                    enabledItem.setCheckState(Qt.Checked)
                    enabledItem.setFlags(enabledItem.flags()
                                         & Qt.ItemIsEditable)
                    ODKfieldItem.setFlags(ODKfieldItem.flags()
                                          & Qt.ItemIsEditable)
                    QGISfieldItem.setFlags(QGISfieldItem.flags()
                                           & Qt.ItemIsEditable)
예제 #60
0
    def func_refreshList(self):
        self.listDev.setCurrentCell(-1, -1)
        self.listDev.clearContents()
        for i in range(self.listDev.rowCount()):
            self.listDev.removeRow(0)

        pos_h = 0

        if not os.path.exists("/var/lib/sixad/profiles/"):
            os.mkdir("/var/lib/sixad/profiles/")

        if not os.path.exists("/var/lib/sixad/profiles/default"):
            dev = shared.func_checkDeviceOptions("default")
            self.listDev.insertRow(pos_h)
            self.listDev.setItem(pos_h, 0, QTableWidgetItem("default"))
            self.listDev.setItem(pos_h, 1, QTableWidgetItem(dev[0]))
            self.listDev.setItem(pos_h, 2, QTableWidgetItem(dev[1]))
            self.listDev.setItem(pos_h, 3, QTableWidgetItem(dev[2]))
            pos_h += 1

        if not os.path.exists("/var/lib/sixad/profiles/hidraw"):
            dev = shared.func_checkDeviceOptions("hidraw")
            self.listDev.insertRow(pos_h)
            self.listDev.setItem(pos_h, 0, QTableWidgetItem("hidraw"))
            self.listDev.setItem(pos_h, 1, QTableWidgetItem(dev[0]))
            self.listDev.setItem(pos_h, 2, QTableWidgetItem(dev[1]))
            self.listDev.setItem(pos_h, 3, QTableWidgetItem(dev[2]))
            pos_h += 1

        devs = os.listdir("/var/lib/sixad/profiles/")
        for i in range(len(devs)):
            pos = i + pos_h
            dev = shared.func_checkDeviceOptions(devs[i])
            self.listDev.insertRow(pos)
            self.listDev.setItem(pos, 0, QTableWidgetItem(devs[i]))
            self.listDev.setItem(pos, 1, QTableWidgetItem(dev[0]))
            self.listDev.setItem(pos, 2, QTableWidgetItem(dev[1]))
            self.listDev.setItem(pos, 3, QTableWidgetItem(dev[2]))

        self.listProf.clear()
        files = os.listdir(os.getenv("HOME") + "/.qtsixa2/profiles/")
        for f in range(len(files)):
            self.listProf.addItem(files[f])
        self.listProf.sortItems()