def __init__(self, choicesJson, valueType, parent=None):
        """Constructor."""
        super(QgisODKChoices, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        self.choicesJson = choicesJson
        choicesDict = json.loads(choicesJson)
        self.choicesTable.setColumnCount(2)
        self.choicesTable.setRowCount(len(choicesDict))
        self.choicesTable.verticalHeader().setVisible(False)
        self.choicesTable.setHorizontalHeaderItem(0,
                                                  QTableWidgetItem("Values"))
        self.choicesTable.setHorizontalHeaderItem(1,
                                                  QTableWidgetItem("Labels"))
        self.choicesTable.setColumnWidth(0, 127)
        self.choicesTable.setColumnWidth(1, 127)
        for i, choice in enumerate(choicesDict):
            choiceValueWidget = QTableWidgetItem(valueType)
            choiceLabelWidget = QTableWidgetItem()
            choiceValueWidget.setData(Qt.EditRole, choice)
            self.choicesTable.setItem(i, 0, choiceValueWidget)
            choiceLabelWidget.setData(Qt.EditRole, choicesDict[choice])
            self.choicesTable.setItem(i, 1, choiceLabelWidget)
        self.choicesTable.sortItems(1)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        self.rowAddButton.clicked.connect(self.rowAddAction)
        self.rowRemoveButton.clicked.connect(self.rowRemoveAction)
Exemple #2
0
    def populateTableWidget(self, selectedLog=None):
        logger.debug(">>populateTableWidget()")
        selected = None

        self.parametersTableWidget.clear()
        self.parametersTableWidget.setSortingEnabled(False)
        self.parametersTableWidget.setRowCount(
            len(self._parameterTableModel._parameters))
        self.parametersTableWidget.setColumnCount(
            len(self._parameterTableModel.HEADERS))
        self.parametersTableWidget.setHorizontalHeaderLabels(
            self._parameterTableModel.HEADERS)
        for row, parameter in enumerate(self._parameterTableModel._parameters):
            item = QTableWidgetItem(parameter.mnemonic)
            item.setData(Qt.UserRole, str(id(parameter)))

            self.parametersTableWidget.setItem(row,
                                               parametertablemodel.MNEMONIC,
                                               item)
            self.parametersTableWidget.setItem(
                row, parametertablemodel.VALUE,
                QTableWidgetItem(parameter.value))
            self.parametersTableWidget.setItem(
                row, parametertablemodel.UNIT,
                QTableWidgetItem(parameter.unit))
            self.parametersTableWidget.setItem(
                row, parametertablemodel.DESCRIPTION,
                QTableWidgetItem(parameter.description))
        self.parametersTableWidget.setSortingEnabled(True)
        self.parametersTableWidget.resizeColumnsToContents()
        if selected is not None:
            selected.setSelected(True)
            self.parametersTableWidget.setCurrentItem(selected)
Exemple #3
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
Exemple #4
0
    def populateTable(self,filePath):
        self.filePath = filePath
        ui = self
        table = ui.tableWidget
#        table.clear()
        table.setRowCount(0)
        xml = file(filePath).read()
        d = QtXml.QDomDocument()
        d.setContent(xml)
        maps = d.elementsByTagName("maplayer")
        self.maps=maps

        for i in range(maps.length()):
            table.setRowCount(table.rowCount()+1)
            info = getMapInfo(maps.item(i))
            nameItem = QTableWidgetItem(info['name'])
            nameItem.setFlags(QtCore.Qt.ItemIsUserCheckable|QtCore.Qt.ItemIsSelectable|QtCore.Qt.ItemIsEnabled)
            nameItem.setCheckState(QtCore.Qt.Unchecked)
            nameItem.setData(QtCore.Qt.UserRole,str(i))
            table.setItem(i,0,nameItem)
            table.setItem(i,1,FixedWidgetItem(info['mtype']))
            table.setItem(i,2,FixedWidgetItem(info['geom']))
            table.setItem(i,3,FixedWidgetItem(info['provider']))
            ds = FixedWidgetItem(info['ds'])
            ds.setData(QtCore.Qt.ToolTipRole,info['ds'])
            table.setItem(i,4,ds)
Exemple #5
0
 def setData(self, role, value):
     if role == Qt.CheckStateRole:
         if value == Qt.Checked:
             self.__parent.checked[self.event()] = True
         else:
             self.__parent.checked[self.event()] = False
     QTableWidgetItem.setData(self, role, value)
Exemple #6
0
    def __populateLengths(self, selectedDim=None):
        selected = None
        self.ui.dimTableWidget.clear()
        self.ui.dimTableWidget.setRowCount(self.rank)

        while self.rank > len(self.lengths):
            self.lengths.append(None)

        headers = ["Length"]
        self.ui.dimTableWidget.setColumnCount(len(headers))
        self.ui.dimTableWidget.setHorizontalHeaderLabels(headers)
        self.ui.dimTableWidget.setVerticalHeaderLabels(
            [unicode(l + 1) for l in range(self.rank)])
        for row, ln in enumerate(self.lengths):
            if ln:
                item = QTableWidgetItem(unicode(ln))
            else:
                item = QTableWidgetItem("")
            item.setData(Qt.UserRole, QVariant(long(row)))
            if selectedDim is not None and selectedDim == row:
                selected = item
            self.ui.dimTableWidget.setItem(row, 0, item)
        self.ui.dimTableWidget.resizeColumnsToContents()
        self.ui.dimTableWidget.horizontalHeader().setStretchLastSection(True)
        if selected is not None:
            selected.setSelected(True)
            self.ui.dimTableWidget.setCurrentItem(selected)
            self.ui.dimTableWidget.editItem(selected)
    def _show_node_information(self, node):
        
        # hide all rows
        for r in range(self.info_table.rowCount()):
            self.info_table.setRowHidden(r, True)
        
        # add new information save dict[ecu_id][settings_id] = row_nr
        comp_id = node.settings_dict['comp_id']      
        self.selection_label.setText("Selected ECU:      %s" % comp_id)

        for set_key in node.settings_dict.keys():
            
            # if already exists -> show its row and skip
            try: 
                row_nr = self._show_dict[comp_id][set_key]
                self.info_table.setRowHidden(row_nr, False)
                continue
            except: pass
                        
            # else add it to table and show row
            self.info_table.setRowCount(self.info_table.rowCount() + 1)
            row_nr = self.info_table.rowCount()          
            item_1 = QTableWidgetItem()
            item_1.setData(QtCore.Qt.EditRole, set_key)  
            item_2 = QTableWidgetItem()
            item_2.setText(str(node.settings_dict[set_key]));  
            General().add_to_three_dict(self._show_dict, comp_id, set_key, row_nr)            
            self.info_table.setItem(row_nr - 1, 0, item_1)
            self.info_table.setItem(row_nr - 1, 1, item_2)
            self.info_table.setRowHeight(row_nr - 1, 20)
Exemple #8
0
    def _show_node_information(self, node):

        # hide all rows
        for r in range(self.info_table.rowCount()):
            self.info_table.setRowHidden(r, True)

        # add new information save dict[ecu_id][settings_id] = row_nr
        comp_id = node.settings_dict['comp_id']
        self.selection_label.setText("Selected ECU:      %s" % comp_id)

        for set_key in node.settings_dict.keys():

            # if already exists -> show its row and skip
            try:
                row_nr = self._show_dict[comp_id][set_key]
                self.info_table.setRowHidden(row_nr, False)
                continue
            except:
                pass

            # else add it to table and show row
            self.info_table.setRowCount(self.info_table.rowCount() + 1)
            row_nr = self.info_table.rowCount()
            item_1 = QTableWidgetItem()
            item_1.setData(QtCore.Qt.EditRole, set_key)
            item_2 = QTableWidgetItem()
            item_2.setText(str(node.settings_dict[set_key]))
            General().add_to_three_dict(self._show_dict, comp_id, set_key,
                                        row_nr)
            self.info_table.setItem(row_nr - 1, 0, item_1)
            self.info_table.setItem(row_nr - 1, 1, item_2)
            self.info_table.setRowHeight(row_nr - 1, 20)
Exemple #9
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(''))
Exemple #10
0
    def refreshPlotTable(self):
        '''
        Refresh the table of plots
        '''
        table = self.dlg.plotTable

        # empty previous content
        for row in range(table.rowCount()):
            table.removeRow(row)
        table.setRowCount(0)

        # Add lines
        for pid, p in self.dataPlotTraces.items():
            # Set row and column count
            twRowCount = table.rowCount()

            # add a new line
            table.setRowCount(twRowCount + 1)

            # Id
            newItem = QTableWidgetItem()
            newItem.setData(Qt.EditRole, pid)
            table.setItem(twRowCount, 0, newItem)

            # Type
            newItem = QTableWidgetItem()
            newItem.setData(Qt.EditRole, p.plot_type)
            table.setItem(twRowCount, 1, newItem)
Exemple #11
0
    def set_inspection(self, projectId, sectionId, inspectionId):
        self.clearContents()

        self.projectId = projectId
        self.sectionId = sectionId
        self.inspectionId = inspectionId

        for r in range(self.rowCount() - 1, -1, -1):
            self.removeRow(r)

        if self.projectId is None or self.sectionId is None or self.inspectionId is None:
            return

        for o_id, obs in self.data[self.projectId]['Sections'][self.sectionId]['Inspections'][self.inspectionId]['Observations'].iteritems():
            r = self.rowCount()
            self.insertRow(r)

            for c, col in enumerate(ColumnData):
                item = QTableWidgetItem(u'{}'.format(obs[col] if c < 6 else ''))
                if c in (0,6):
                    data_column = 'Import' if c == 0 else 'ForceImport'
                    item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable)
                    item.setCheckState(Qt.Checked if obs[data_column] else Qt.Unchecked)
                    item.setData(Qt.UserRole, o_id)
                    item.setData(Qt.UserRole+1, data_column)
                else:
                    item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                font = item.font()
                font.setPointSize(font.pointSize() - 2)
                item.setFont(font)
                self.setItem(r, c, item)

        self.resizeColumnsToContents()
Exemple #12
0
    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
Exemple #13
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(''))
Exemple #14
0
    def refreshPlotTable(self):
        '''
        Refresh the table of plots
        '''
        table = self.dlg.plotTable

        # empty previous content
        for row in range(table.rowCount()):
            table.removeRow(row)
        table.setRowCount(0)

        # Add lines
        for pid, p in self.dataPlotTraces.items():
            # Set row and column count
            twRowCount = table.rowCount()

            # add a new line
            table.setRowCount( twRowCount + 1 )

            # Id
            newItem = QTableWidgetItem()
            newItem.setData( Qt.EditRole, pid )
            table.setItem(twRowCount, 0, newItem)

            # Type
            newItem = QTableWidgetItem()
            newItem.setData( Qt.EditRole, p.plot_type )
            table.setItem(twRowCount, 1, newItem)
Exemple #15
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(''))
Exemple #16
0
 def populateVars(self, selectedVar=None):
     selected = None
     self.ui.varTableWidget.clear()
     self.ui.varTableWidget.setSortingEnabled(False)
     self.ui.varTableWidget.setRowCount(len(self.__vars))
     headers = ["Name", "Value", "Info"]
     self.ui.varTableWidget.setColumnCount(len(headers))
     self.ui.varTableWidget.setHorizontalHeaderLabels(headers)
     for row, name in enumerate(sorted(self.__vars.keys())):
         item = QTableWidgetItem(name)
         item.setData(Qt.UserRole, QVariant(name))
         flags = item.flags()
         flags ^= Qt.ItemIsEditable
         item.setFlags(flags)
         self.ui.varTableWidget.setItem(row, 0, item)
         item2 = QTableWidgetItem(self.__vars[name] or "")
         self.ui.varTableWidget.setItem(row, 1, item2)
         item3 = QTableWidgetItem(self.__pardesc[name]['doc'] or "")
         flags = item3.flags()
         flags &= ~Qt.ItemIsEnabled
         item3.setFlags(flags)
         self.ui.varTableWidget.setItem(row, 2, item3)
         if selectedVar is not None and selectedVar == name:
             selected = item2
     self.ui.varTableWidget.setSortingEnabled(True)
     self.ui.varTableWidget.resizeColumnsToContents()
     self.ui.varTableWidget.horizontalHeader()\
         .setStretchLastSection(True)
     if selected is not None:
         selected.setSelected(True)
         self.ui.varTableWidget.setCurrentItem(selected)
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(''))
Exemple #18
0
 def change_all_rows(new_rows):
     for i in xrange(table_widget.rowCount(), -1, -1):
         table_widget.removeRow(i)
     for i, value in enumerate(new_rows):
         item = QTableWidgetItem()
         item.setData(Qt.EditRole, value)
         table_widget.insertRow(i)
         table_widget.setItem(i, 0, item)
    def onAddVariableClicked(self):
        '''
        Add a variable to the list from the text input
        when the user clicks on the corresponding button
        '''
        if not self.initDone:
            return

        # Get table and row count
        tw = self.dlg.twVariableList
        twRowCount = tw.rowCount()

        # Get input data
        vname = unicode(self.dlg.inVariableName.text()).strip(' \t')
        vvalue = unicode(self.dlg.inVariableValue.text()).strip(' \t')

        # Check if the variable if not already in the list
        if vname in self.variableList:
            self.updateLog( self.tr(u'This variable is already in the list') )
            return

        # Add constraint of possible input values
        p = re.compile('^[a-zA-Z]+$')
        if not p.match( vname ):
            self.updateLog( self.tr(u'The variable must contain only lower case ascii letters !') )
            return

        # Set table properties
        tw.setRowCount(twRowCount + 1)
        tw.setColumnCount( 2 )

        # Empty the name text input
        self.dlg.inVariableName.setText(u'')

        # Add the new "variable" item to the table
        # name
        newItem = QTableWidgetItem()
        newItem.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled  )
        newItem.setData( Qt.EditRole, vname )
        tw.setItem(twRowCount, 0, newItem)

        # value
        newItem = QTableWidgetItem()
        newItem.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled )
        newItem.setData( Qt.EditRole, vvalue )
        tw.setItem(twRowCount, 1, newItem)

        # Add variable to the list
        self.variableList.append( vname )

        # Add variable to the project
        p = QgsProject.instance()
        p.writeEntry( 'PluginDynamicLayers', 'VariableList', self.variableList )
        p.setDirty( True )
Exemple #20
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.widget_layout = QVBoxLayout()
        self.table_widget = QTableWidget(106, 1)
        self.table_widget.setSortingEnabled(True)

        self.widget_layout.addWidget(self.table_widget)
        self.setLayout(self.widget_layout)

        for num in range(101):
            item = QTableWidgetItem()
            item.setData(Qt.EditRole, num)
            self.table_widget.setItem(num, 0, item)
Exemple #21
0
def table_test():
	"""
	Messing around with QTableWidgets

	This successfully creates a table of DateTimes and allows you to edit them.
	"""

	from PyQt4.QtGui import QTableWidget, QTableWidgetItem, QItemEditorCreatorBase, QDateTimeEdit, QItemEditorFactory, QStyledItemDelegate
	from PyQt4.QtCore import QVariant, QDateTime, QObject

	class DateTimeEditorCreator(QItemEditorCreatorBase):
		"""
		See gui/itemviews/qitemeditorfactory.cpp for implementations of
		createEditor() and valuePropertyName()
		"""
		def __init__(self):
			QItemEditorCreatorBase.__init__(self)

		def createWidget(self, parent):
			wid = QDateTimeEdit(parent)
			wid.setCalendarPopup(True)
			wid.setFrame(False)
			return wid

		def valuePropertyName(self):
			return "dateTime"

	def die():
		raise MyError("Oops")

	class MyError(Exception):
		def __init__(self, value):
			self.value = value
		def __str__(self):
			return repr(self.value)

	tableWidget = QTableWidget(12, 3)
	tableWidget.setItemDelegate(QStyledItemDelegate())
	tableWidget.itemDelegate().setItemEditorFactory(QItemEditorFactory())
	tableWidget.itemDelegate().itemEditorFactory().registerEditor(QVariant.DateTime, DateTimeEditorCreator())
	for row in range(10):
		for col in range(3):
			date = QDateTime.currentDateTime()
			string = str(row) + ',' + str(col)
			item = QTableWidgetItem()
			item.setData(Qt.DisplayRole, QVariant(date))
			tableWidget.setItem(row, col, item)
	tableWidget.show()
	sys.exit(app.exec_())
Exemple #22
0
 def runFinishedFromThread(self, success):
     self.testThread.stop()
     QApplication.restoreOverrideCursor()
     self.buttonOk.setEnabled(True)
     if success == "writeShape":
         extra = ""
         if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(
                 unicode(self.shapefileName))
             if not addCanvasCheck:
                 QMessageBox.warning(
                     self, self.tr("Geometry"),
                     self.tr("Error loading output shapefile:\n%s") %
                     (unicode(self.shapefileName)))
         else:
             QMessageBox.information(
                 self, self.tr("Geometry"),
                 self.tr("Created output shapefile:\n%s\n%s") %
                 (unicode(self.shapefileName), extra))
     else:
         self.tblUnique.setColumnCount(2)
         count = 0
         for rec in success:
             if len(rec[1]) < 1:
                 continue
             for err in rec[1]:  # for each error we find
                 self.tblUnique.insertRow(count)
                 fidItem = QTableWidgetItem(unicode(rec[0]))
                 self.tblUnique.setItem(count, 0, fidItem)
                 message = err.what()
                 errItem = QTableWidgetItem(message)
                 if err.hasWhere(
                 ):  # if there is a location associated with the error
                     errItem.setData(Qt.UserRole, err.where())
                 self.tblUnique.setItem(count, 1, errItem)
                 count += 1
         self.tblUnique.setHorizontalHeaderLabels(
             [self.tr("Feature"), self.tr("Error(s)")])
         self.tblUnique.horizontalHeader().setResizeMode(
             0, QHeaderView.ResizeToContents)
         self.tblUnique.horizontalHeader().show()
         self.tblUnique.horizontalHeader().setResizeMode(
             1, QHeaderView.Stretch)
         self.tblUnique.resizeRowsToContents()
         self.lstCount.insert(unicode(count))
     self.cancel_close.setText("Close")
     QObject.disconnect(self.cancel_close, SIGNAL("clicked()"),
                        self.cancelThread)
     return True
Exemple #23
0
    def place_entries(self, entries):
        table = self.ui.table

        j = -1
        for h in entries:
            j += 1

            if not '_details' in h:
                h['_details'] = json.loads(h['details']) if h['details'] else {
                    "short": h['description'],
                    "plus": "",
                    "minus": "",
                    "icon": None
                }
                # TODO: remove this block
                if not ('icon' in h['_details']):  #
                    h['_details']['icon'] = None  #
            if not ('_icon' in h):
                h['_icon'] = ":/op/images/op/" + h['_details'][
                    'icon'] + ".png" if h['_details']['icon'] else None
            description = h["_details"]["short"] or h['description']

            table.insertRow(j)

            item = QTableWidgetItem(str(h["date"]))
            item.setData(99, h)
            table.setItem(j, 0, item)
            icon = qicon(h["_icon"])
            item.setIcon(icon)

            set_col(table, j, 1, description)
            set_col(table,
                    j,
                    2,
                    h["_details"]["plus"],
                    color=COLOR_GREEN,
                    align="right")
            set_col(table,
                    j,
                    3,
                    h["_details"]["minus"],
                    color=COLOR_RED,
                    align="right")

            if h["memo"] > 0:
                icon = qicon(":/icons/images/memo.png")
                table.item(j, 1).setIcon(icon)
Exemple #24
0
def load_table(table, headers, data, checkFirstColumn=True):
    table.setHorizontalHeaderLabels(headers)
    table.horizontalHeader().setStretchLastSection(True)
    table.setSelectionBehavior(QAbstractItemView.SelectRows)
    for i in xrange(table.rowCount()):
        table.removeRow(0)
    for r, row in enumerate(data):
        table.insertRow(r)
        for index, colItem in enumerate(row):
            item = QTableWidgetItem(colItem)
            table.setItem(r, index, item)
            if index == 0 and checkFirstColumn:
                item.setData(Qt.UserRole, row)
                item.setCheckState(Qt.Unchecked)
                item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
            else:
                item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
Exemple #25
0
def load_datatools_csv(table, headers, data):
    columns = len(headers)
    table.setColumnCount(columns)
    remove_rows(table)

    for rw in range(len(data[0])):
        table.insertRow(rw)
        for c in range(len(data)):
            item = QTableWidgetItem(str(data[c][rw]))
            table.setItem(rw, c, item)
            item.setData(Qt.UserRole, rw)
            item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

    # table options
    load_table_options(table, headers)

    # auto fit
    auto_fit_table(table)
Exemple #26
0
def load_datatools(table, headers, data):
    _columns = len(headers)
    table.setColumnCount(_columns)
    remove_rows(table)

    for rw, row in enumerate(data):
        table.insertRow(rw)
        for index, colItem in enumerate(row):
            item = QTableWidgetItem(str(colItem))
            table.setItem(rw, index, item)
            item.setData(Qt.UserRole, row)
            item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

    # table options
    load_table_options(table, headers)

    # auto fit
    auto_fit_table(table)
Exemple #27
0
def load_table(table, headers, data, checkFirstColumn=True):
    table.setHorizontalHeaderLabels(headers)
    table.horizontalHeader().setStretchLastSection(True)
    table.setSelectionBehavior(QAbstractItemView.SelectRows)
    for i in range(table.rowCount()):
        table.removeRow(0)
    for r, row in enumerate(data):
        table.insertRow(r)
        for index, colItem in enumerate(row):
            item = QTableWidgetItem(colItem)
            table.setItem(r, index, item)
            if index == 0 and checkFirstColumn:
                item.setData(Qt.UserRole, row)
                item.setCheckState(Qt.Unchecked)
                item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled
                              | Qt.ItemIsUserCheckable)
            else:
                item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
    def populateLayersTable(self, foo=None, foo2=None, foo3=None):
        """ List vector layers that support changes in attributes and are writable.
            Arguments are 3 and optional because this function listens to several
            SIGNALs.
        """

        # Initialize Layers Table
        self.tblLayers.clearContents()
        self.tblLayers.setRowCount(0)

        vLayers = []
        for layer in QgsMapLayerRegistry.instance().mapLayers().values():
            if layer.type() == QgsMapLayer.VectorLayer:
                if layer.dataProvider().capabilities(
                ) & QgsVectorDataProvider.ChangeAttributeValues:
                    if not layer.isReadOnly():
                        if layer.geometryType(
                        ) < 3:  # Avoid UnknownGeometry and NoGeometry
                            vLayers.append(layer)

        self.tblLayers.setRowCount(len(vLayers))
        self.tblLayers.setColumnCount(3)

        self.tblLayers.setSortingEnabled(False)
        for row, lyr in enumerate(vLayers):
            item = QTableWidgetItem( QIcon( ":/plugins/AutoFields/icons/" + \
                self.geometryDict[lyr.geometryType()] + ".png"),
                str( lyr.geometryType() ) )
            self.tblLayers.setItem(row, 0, item)

            item = QTableWidgetItem(lyr.name())
            item.setData(Qt.UserRole, lyr.id())
            self.tblLayers.setItem(row, 1, item)

            tmpTreeLayer = self.root.findLayer(lyr.id())
            if tmpTreeLayer:
                group = tmpTreeLayer.parent().name()
                self.tblLayers.setItem(
                    row, 2,
                    QTableWidgetItem(
                        group if group else QApplication.
                        translate("AutoFieldsDockWidgetPy", "< root >")))

        self.tblLayers.setSortingEnabled(True)
Exemple #29
0
    def addCorrector(self, idx):
        if not self._corlst1.selectedItems(): return
        #print self._corlst1.itemFromIndex(idx).text(0)
        nrow = self.table4.rowCount()
        if nrow >= self._nmax:
            QtGui.QMessageBox.critical(
                self, "Local Orbit Bump", 
                "ERROR: We need only {0} correctors.".format(self._nmax),
                QtGui.QMessageBox.Ok)
                #self.progress.setValue(0)
            return
        self.table4.setRowCount(nrow+1)
        it0 = self._corlst1.selectedItems()[-1]
        icor, ok = it0.data(0, Qt.UserRole).toInt()
        if icor < 0: return
        newc = self._cors[icor]
        for j in range(self.table4.columnCount()):
            it = QTableWidgetItem()
            if j > 0: it.setTextAlignment(
                Qt.AlignRight | Qt.AlignVCenter)
            header = self.table4.horizontalHeaderItem(j)
            if header.text() != "dBump":
                it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            else:
                it.setData(Qt.DisplayRole, "0")
                it.setData(Qt.UserRole, 0.0)
            self.table4.setItem(nrow, j, it)
        self.table4.item(nrow,0).setData(Qt.UserRole, icor)
        for j,h in [(0, "Element"), (1, "s [m]")]:
            self.table4.item(nrow,j).setData(Qt.DisplayRole,
                                          it0.text(self._header[h]))
        for j in range(self._corlst1.columnCount()):
            it0.setForeground(j, Qt.red)
        it0.setDisabled(True)
        self.emit(SIGNAL("correctorAdded(PyQt_PyObject)"), newc)
        # use initial values

        self.updateTwiss()
        self.updateCorReadings()
        self.table4.resizeColumnsToContents()
        if self.table4.rowCount() == self._nmax:
            #print "All correctors are ready"
            self.emit(SIGNAL("correctorsComplete()"))
Exemple #30
0
    def addCorrector(self, idx):
        if not self._corlst1.selectedItems(): return
        #print self._corlst1.itemFromIndex(idx).text(0)
        nrow = self.table4.rowCount()
        if nrow >= self._nmax:
            QtGui.QMessageBox.critical(
                self, "Local Orbit Bump",
                "ERROR: We need only {0} correctors.".format(self._nmax),
                QtGui.QMessageBox.Ok)
                #self.progress.setValue(0)
            return
        self.table4.setRowCount(nrow+1)
        it0 = self._corlst1.selectedItems()[-1]
        icor, ok = it0.data(0, Qt.UserRole).toInt()
        if icor < 0: return
        newc = self._cors[icor]
        for j in range(self.table4.columnCount()):
            it = QTableWidgetItem()
            if j > 0: it.setTextAlignment(
                Qt.AlignRight | Qt.AlignVCenter)
            header = self.table4.horizontalHeaderItem(j)
            if header.text() != "dBump":
                it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            else:
                it.setData(Qt.DisplayRole, "0")
                it.setData(Qt.UserRole, 0.0)
            self.table4.setItem(nrow, j, it)
        self.table4.item(nrow,0).setData(Qt.UserRole, icor)
        for j,h in [(0, "Element"), (1, "s [m]")]:
            self.table4.item(nrow,j).setData(Qt.DisplayRole,
                                          it0.text(self._header[h]))
        for j in range(self._corlst1.columnCount()):
            it0.setForeground(j, Qt.red)
        it0.setDisabled(True)
        self.emit(SIGNAL("correctorAdded(PyQt_PyObject)"), newc)
        # use initial values

        self.updateTwiss()
        self.updateCorReadings()
        self.table4.resizeColumnsToContents()
        if self.table4.rowCount() == self._nmax:
            #print "All correctors are ready"
            self.emit(SIGNAL("correctorsComplete()"))
 def addAutoFieldToAutoFieldsTable( self, autoFieldId, autoField ):
     """ Add a whole row to the AutoFields table """
     row = self.tblAutoFields.rowCount()
     self.tblAutoFields.insertRow( row )
     name = autoField['layer']
     if 'layerId' in autoField:
         lyr = QgsMapLayerRegistry.instance().mapLayer( autoField['layerId'] )
         name = lyr.name()
     item = QTableWidgetItem( name )
     item.setData( Qt.UserRole, autoFieldId )
     item.setData( Qt.ToolTipRole, autoField['layer'] )
     self.tblAutoFields.setItem( row, 0, item )
     item = QTableWidgetItem( autoField['field'] )
     self.tblAutoFields.setItem( row, 1, item )
     item = QTableWidgetItem( autoField['expression'] )
     self.tblAutoFields.setItem( row, 2, item )
     item = QTableWidgetItem( QApplication.translate( "ExportAutoFields",
         "Enabled" ) if autoField['enabled'] else QApplication.translate( "ExportAutoFields", "Disabled" ) )
     self.tblAutoFields.setItem( row, 3, item )
Exemple #32
0
def set_col(table, row, col, val, fmt=None, color=None, align=None, editable=None, data=None):
	item = QTableWidgetItem(fmt % val if fmt else str(val))
	if color:
		item.setForeground(QtGui.QColor(color))
	if align=="right":
		item.setTextAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
	if align=="center":
		item.setTextAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
	if not(editable is None):
		if editable:
			item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
				| QtCore.Qt.ItemIsEditable)
		else:
			item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
	if data:
		item.setData(99, data)
	
	table.setItem(row, col, item)
	return item
Exemple #33
0
    def populateCheckboxTable(self):
        ''' populate QTableWidget manually with log names and checkboxes 
        simpler than using a QTableView and a dedicated model such as
        tableModel = LogLayoutTableModel(self, logList = self._logs, logHeaders = headers)
        self.tableView.setModel(tableModel)
        '''
        logger.debug(">>populateCheckboxTable()")
        selected = None

        initialTracks = len(self._logs)
        if len(self._initialPlotList) > initialTracks:
            initialTracks = len(self._initialPlotList)

        #add an extra log name column and a blank end column
        totalNumColumns = initialTracks + 2
        logger.debug("--populateCheckboxTable() totalNumColumns:{0}".format(
            totalNumColumns))
        if (self._logs != None) and (len(self._logs) > 0):
            self.headers = self.getLayoutTableHeaders(initialTracks + 1)

            self.chkboxTableWidget.clear()
            self.chkboxTableWidget.setSortingEnabled(False)
            self.chkboxTableWidget.setRowCount(len(self._logs))
            self.chkboxTableWidget.setColumnCount(len(self.headers))
            self.chkboxTableWidget.setHorizontalHeaderLabels(self.headers)

            for row, log in enumerate(self._logs):
                item = QTableWidgetItem(log.name)
                #looks like can set an object as data
                item.setData(Qt.UserRole, log)
                self.chkboxTableWidget.setItem(row, 0, item)
                for i in range(1, totalNumColumns):
                    chkBoxItem = self._layoutHandler.createChkBoxItem(log)
                    self.chkboxTableWidget.setItem(row, i, chkBoxItem)

            self.chkboxTableWidget.resizeColumnsToContents()
            self._layoutHandler.tickDisplayedLogs()
            self.chkboxTableWidget.itemChanged.connect(self.changeLogTrack)
        else:
            logger.debug(
                "--populateCheckboxTable() _logs==None: {0}, _logs length: {1}"
                .format((self._logs == None), (len(self._logs))))
    def populate_function_table_1(self):
        """Populate the tblFunctions1 table with available functions."""
        hazards = deepcopy(hazard_all)
        exposures = exposure_all

        self.lblAvailableFunctions1.clear()
        self.tblFunctions1.clear()
        self.tblFunctions1.setColumnCount(len(hazards))
        self.tblFunctions1.setRowCount(len(exposures))
        for i in range(len(hazards)):
            hazard = hazards[i]
            item = QTableWidgetItem()
            item.setIcon(QIcon(get_image_path(hazard)))
            item.setText(hazard['name'].capitalize())
            item.setTextAlignment(Qt.AlignLeft)
            self.tblFunctions1.setHorizontalHeaderItem(i, item)
        for i in range(len(exposures)):
            exposure = exposures[i]
            item = QTableWidgetItem()
            item.setIcon(QIcon(get_image_path(exposure)))
            item.setText(exposure['name'].capitalize())
            self.tblFunctions1.setVerticalHeaderItem(i, item)
        developer_mode = setting('developer_mode', False, bool)
        for hazard in hazards:
            for exposure in exposures:
                item = QTableWidgetItem()
                if (exposure in hazard['disabled_exposures']
                        and not developer_mode):
                    background_colour = unavailable_option_color
                    # Set it disable and un-selectable
                    item.setFlags(item.flags() & ~Qt.ItemIsEnabled
                                  & ~Qt.ItemIsSelectable)
                else:
                    background_colour = available_option_color
                item.setBackground(QBrush(background_colour))
                item.setFont(big_font)
                item.setTextAlignment(Qt.AlignCenter | Qt.AlignHCenter)
                item.setData(RoleHazard, hazard)
                item.setData(RoleExposure, exposure)
                self.tblFunctions1.setItem(exposures.index(exposure),
                                           hazards.index(hazard), item)
        self.parent.pbnNext.setEnabled(False)
Exemple #35
0
    def populateTableWidget(self, selectedLog=None):
        logger.debug(">>populateTableWidget()")
        selected = None
        self.logsTableWidget.clear()
        self.logsTableWidget.setSortingEnabled(False)
        self.logsTableWidget.setRowCount(len(self._logTableModel.logs))
        self.logsTableWidget.setColumnCount(len(self._logTableModel.HEADERS))
        self.logsTableWidget.setHorizontalHeaderLabels(
            self._logTableModel.HEADERS)
        for row, log in enumerate(self._logTableModel.logs):
            item = QTableWidgetItem(log.name)
            item.setData(Qt.UserRole, str(id(log)))
            localLogType = LogType.findLogTypeFromMnemonic(log.fileMnemonic)
            if selectedLog is not None and selectedLog == id(log):
                selected = item
            chkBoxItem = QtGui.QTableWidgetItem()
            chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable
                                | QtCore.Qt.ItemIsEnabled)
            chkBoxItem.setCheckState(QtCore.Qt.Unchecked)
            #is this needed?
            chkBoxItem.setData(Qt.UserRole, str(id(log)))

            self.logsTableWidget.setItem(row, logtablemodel.IMPORT, chkBoxItem)
            self.logsTableWidget.setItem(row, logtablemodel.NAME, item)
            self.logsTableWidget.setCellWidget(
                row, logtablemodel.TYPE,
                self.getPreparedTypesCombo(log.fileMnemonic))
            self.logsTableWidget.setCellWidget(
                row, logtablemodel.UNIT,
                self.populateUnitsCombo(localLogType, log.fileUnit))
            self.logsTableWidget.setItem(row, logtablemodel.FILE_MNEMONIC,
                                         QTableWidgetItem(log.fileMnemonic))
            self.logsTableWidget.setItem(row, logtablemodel.FILE_UNIT,
                                         QTableWidgetItem(log.fileUnit))
            self.logsTableWidget.setItem(row, logtablemodel.FILE_DESCRIPTION,
                                         QTableWidgetItem(log.fileDescription))
        self.logsTableWidget.setSortingEnabled(True)
        self.logsTableWidget.resizeColumnsToContents()

        if selected is not None:
            selected.setSelected(True)
            self.logsTableWidget.setCurrentItem(selected)
 def displayColumns(self):
     self.clear()
     for c in range(self.columnCount() - 1, -1, -1):
         self.removeColumn(c)
     for r in range(self.rowCount() - 1, -1, -1):
         self.removeRow(r)
     columns = self.settings.value("columns")
     c = 0
     for i, col in enumerate(columnVarSetting):
         if col in columns:
             if columnRowName[i] == "changedGeometryStr" and not self.geomColumn:
                 continue
             self.insertColumn(c)
             item = QTableWidgetItem(columnFancyName[i])
             item.setData(Qt.UserRole, columnRowName[i])
             font = item.font()
             font.setPointSize(font.pointSize() - 2)
             item.setFont(font)
             self.setHorizontalHeaderItem(c, item)
             c += 1
     self.horizontalHeader().setMinimumSectionSize(15)
Exemple #37
0
 def addAutoFieldToAutoFieldsTable(self, autoFieldId, autoField):
     """ Add a whole row to the AutoFields table """
     row = self.tblAutoFields.rowCount()
     self.tblAutoFields.insertRow(row)
     name = autoField['layer']
     if 'layerId' in autoField:
         lyr = QgsMapLayerRegistry.instance().mapLayer(autoField['layerId'])
         name = lyr.name()
     item = QTableWidgetItem(name)
     item.setData(Qt.UserRole, autoFieldId)
     item.setData(Qt.ToolTipRole, autoField['layer'])
     self.tblAutoFields.setItem(row, 0, item)
     item = QTableWidgetItem(autoField['field'])
     self.tblAutoFields.setItem(row, 1, item)
     item = QTableWidgetItem(autoField['expression'])
     self.tblAutoFields.setItem(row, 2, item)
     item = QTableWidgetItem(
         QApplication.translate("ExportAutoFields", "Enabled"
                                ) if autoField['enabled'] else QApplication.
         translate("ExportAutoFields", "Disabled"))
     self.tblAutoFields.setItem(row, 3, item)
    def _reloadAnnotationTable(self):
        self.annotationTableWidget.clear()
        self.annotationTableWidget.setRowCount(len(self._annotations))
        self._initAnnotationTableHeader()

        # Flip the key/value of the annotation list so we can sort them by label
        annotations = self._annotations.items()
        annotations = map(
            lambda (coord3d, (label, comment)): (label, coord3d, comment),
            annotations)
        annotations = sorted(annotations)

        for row, (ravelerLabel, coord3d, comment) in enumerate(annotations):
            coordItem = QTableWidgetItem("{}".format(coord3d))
            labelItem = QTableWidgetItem("{}".format(ravelerLabel))
            commentItem = QTableWidgetItem(comment)

            coordItem.setData(Qt.UserRole, (coord3d, ravelerLabel))
            labelItem.setData(Qt.UserRole, (coord3d, ravelerLabel))
            commentItem.setData(Qt.UserRole, (coord3d, ravelerLabel))

            self.annotationTableWidget.setItem(
                row, AnnotationTableColumns.Coordinates, coordItem)
            self.annotationTableWidget.setItem(row,
                                               AnnotationTableColumns.Body,
                                               labelItem)
            self.annotationTableWidget.setItem(row,
                                               AnnotationTableColumns.Comment,
                                               commentItem)
    def populateLayersTable( self, foo=None, foo2=None, foo3=None ):
        """ List vector layers that support changes in attributes and are writable.
            Arguments are 3 and optional because this function listens to several
            SIGNALs.
        """

        # Initialize Layers Table
        self.tblLayers.clearContents()
        self.tblLayers.setRowCount( 0 )

        vLayers = []
        for layer in QgsMapLayerRegistry.instance().mapLayers().values():
            if layer.type() == QgsMapLayer.VectorLayer:
                if layer.dataProvider().capabilities() & QgsVectorDataProvider.ChangeAttributeValues:
                    if not layer.isReadOnly():
                        if layer.geometryType() < 3: # Avoid UnknownGeometry and NoGeometry
                            vLayers.append( layer )

        self.tblLayers.setRowCount( len( vLayers ) )
        self.tblLayers.setColumnCount( 3 )

        self.tblLayers.setSortingEnabled( False )
        for row, lyr in enumerate( vLayers ):
            item = QTableWidgetItem( QIcon( ":/plugins/AutoFields/icons/" + \
                self.geometryDict[lyr.geometryType()] + ".png"),
                str( lyr.geometryType() ) )
            self.tblLayers.setItem( row, 0, item )

            item = QTableWidgetItem( lyr.name() )
            item.setData( Qt.UserRole, lyr.id() )
            self.tblLayers.setItem( row, 1, item )

            tmpTreeLayer = self.root.findLayer( lyr.id() )
            if tmpTreeLayer:
                group = tmpTreeLayer.parent().name()
                self.tblLayers.setItem(row, 2,
                    QTableWidgetItem( group if group else QApplication.translate("AutoFieldsDockWidgetPy",
                        "< root >" ) ) )

        self.tblLayers.setSortingEnabled( True )
Exemple #40
0
def appendRow(theTable, theLabel, theData):
    """ Append new row to table widget.
    :param theTable: a QTable instance
    :param theLabel: label for the row
    :param theData: custom data associated with theLabel value.
    """
    myRow = theTable.rowCount()
    theTable.insertRow(theTable.rowCount())

    myItem = QTableWidgetItem(theLabel)

    # 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((theData,))
    # To retrieve it again you would need to do:
    #myValue = myVariant.toPyObject()[0]
    myItem.setData(Qt.UserRole, myVariant)

    theTable.setItem(myRow, 0, myItem)
    theTable.setItem(myRow, 1, QTableWidgetItem(''))
Exemple #41
0
    def addNodeInIndexList(self, index):
        """
        Add the node wich pointer is index.data(QT.UserRole + 1) in the
        indexedItems list.
        """
        # get the node from the index
        node_ptr = self.selectIndexItems.model().data(index, Qt.UserRole + 1)
        if not node_ptr.isValid():
            return
        added_node = VFS.Get().getNodeFromPointer(node_ptr.toULongLong()[0])

        # add the node.this into the selected items list
        new_item = QTableWidgetItem(QIcon(":/folder.png"), added_node.name())
        new_item.setData(Qt.UserRole + 1, QVariant(long(added_node.this)))
        self.tmp_indexed_items[long(added_node.this)] = False

        new_checkbox = QTableWidgetItem(1);
        new_checkbox.data(Qt.CheckStateRole);
        new_checkbox.setCheckState(Qt.Unchecked);

        self.indexedItems.insertRow(0)
        self.indexedItems.setItem(0, 0, new_item)
        self.indexedItems.setItem(0, 1, new_checkbox)
Exemple #42
0
 def populateAttributes(self, selectedAttribute=None):
     selected = None
     self.ui.attributeTableWidget.clear()
     self.ui.attributeTableWidget.setSortingEnabled(False)
     self.ui.attributeTableWidget.setRowCount(len(self.__attributes))
     headers = ["Name", "Value"]
     self.ui.attributeTableWidget.setColumnCount(len(headers))
     self.ui.attributeTableWidget.setHorizontalHeaderLabels(headers)
     for row, name in enumerate(self.__attributes):
         item = QTableWidgetItem(name)
         item.setData(Qt.UserRole, QVariant(name))
         self.ui.attributeTableWidget.setItem(row, 0, item)
         item2 = QTableWidgetItem(self.__attributes[name])
         self.ui.attributeTableWidget.setItem(row, 1, item2)
         if selectedAttribute is not None and selectedAttribute == name:
             selected = item2
     self.ui.attributeTableWidget.setSortingEnabled(True)
     self.ui.attributeTableWidget.resizeColumnsToContents()
     self.ui.attributeTableWidget.horizontalHeader().\
         setStretchLastSection(True)
     if selected is not None:
         selected.setSelected(True)
         self.ui.attributeTableWidget.setCurrentItem(selected)
    def addAutoFieldToAutoFieldsTable( self, autoField, candidateLayer ):
        """ Add a whole row to the AutoFields table """
        row = self.tblAutoFields.rowCount()
        self.tblAutoFields.insertRow( row )
        layerName = self.ogrLayerName( autoField['layer'] )
        item = QTableWidgetItem( layerName if layerName else autoField['layer'] )
        item.setData( Qt.UserRole, autoField['layer'] )
        item.setData( Qt.ToolTipRole, autoField['layer'] )
        self.tblAutoFields.setItem( row, 0, item )
        item = QTableWidgetItem( autoField['field'] )
        self.tblAutoFields.setItem( row, 1, item )
        item = QTableWidgetItem( autoField['expression'] )
        self.tblAutoFields.setItem( row, 2, item )

        layerCombo = QComboBox()
        layerCombo.addItem( '[Select a layer]', None )
        for layer in self.layers:
           layerCombo.addItem( layer.name(), layer.id() )
        if candidateLayer:
            layerCombo.setCurrentIndex( layerCombo.findData( candidateLayer.id() ) )
        layerCombo.currentIndexChanged.connect( partial( self.layerOrFieldCombosChanged, row ) )
        self.tblAutoFields.setCellWidget( row, 4, layerCombo )

        fieldCombo = QComboBox()
        fieldCombo.addItem( '[Select a field]', None )
        if layerCombo.currentIndex() != 0:
            for field in candidateLayer.fields():
                fieldCombo.addItem( field.name() )
            fieldIndex = fieldCombo.findText( autoField['field'] )
            fieldCombo.setCurrentIndex( fieldIndex if fieldIndex != -1 else 0 )
        fieldCombo.currentIndexChanged.connect( partial( self.layerOrFieldCombosChanged, None ) )
        self.tblAutoFields.setCellWidget( row, 5, fieldCombo )

        label = self.getLabelWithArrow( layerCombo.currentIndex(), fieldCombo.currentIndex(), candidateLayer, autoField['field'] )
        self.tblAutoFields.setCellWidget( row, 3, label )

        self.layerOrFieldCombosChanged( None, None ) # Validate initial load of AutoFields/Layers
Exemple #44
0
 def runFinishedFromThread(self, success):
     self.testThread.stop()
     QApplication.restoreOverrideCursor()
     self.buttonOk.setEnabled(True)
     if success == "writeShape":
         extra = ""
         if self.addToCanvasCheck.isChecked():
             addCanvasCheck = ftools_utils.addShapeToCanvas(unicode(self.shapefileName))
             if not addCanvasCheck:
                 QMessageBox.warning(self, self.tr("Geometry"), self.tr("Error loading output shapefile:\n%s") % (unicode(self.shapefileName)))
         else:
             QMessageBox.information(self, self.tr("Geometry"), self.tr("Created output shapefile:\n%s\n%s") % (unicode(self.shapefileName), extra))
     else:
         self.tblUnique.setColumnCount(2)
         count = 0
         for rec in success:
             if len(rec[1]) < 1:
                 continue
             for err in rec[1]:  # for each error we find
                 self.tblUnique.insertRow(count)
                 fidItem = QTableWidgetItem(unicode(rec[0]))
                 self.tblUnique.setItem(count, 0, fidItem)
                 message = err.what()
                 errItem = QTableWidgetItem(message)
                 if err.hasWhere():  # if there is a location associated with the error
                     errItem.setData(Qt.UserRole, err.where())
                 self.tblUnique.setItem(count, 1, errItem)
                 count += 1
         self.tblUnique.setHorizontalHeaderLabels([self.tr("Feature"), self.tr("Error(s)")])
         self.tblUnique.horizontalHeader().setResizeMode(0, QHeaderView.ResizeToContents)
         self.tblUnique.horizontalHeader().show()
         self.tblUnique.horizontalHeader().setResizeMode(1, QHeaderView.Stretch)
         self.tblUnique.resizeRowsToContents()
         self.lstCount.insert(unicode(count))
     self.cancel_close.setText("Close")
     QObject.disconnect(self.cancel_close, SIGNAL("clicked()"), self.cancelThread)
     return True
 def displayRows(self, observations):
     self.clearContents()
     for r in range(self.rowCount() - 1, -1, -1):
         self.removeRow(r)
     for r, obs in enumerate(observations):
         # obs is a QgsFeature, translate it to a dict
         dataDict = {"type": obs["type"], "x": obs["x"], "y": obs["y"],
                     "observation": obs["observation"], "precision": obs["precision"]}
         self.insertRow(r)
         # type
         item = QTableWidgetItem(obs["type"])
         item.setData(Qt.UserRole, dataDict)
         item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
         item.setCheckState(Qt.Checked)
         self.setItem(r, 0, item)
         # observation
         item = QTableWidgetItem("%.4f" % obs["observation"])
         item.setFlags(Qt.ItemIsEnabled)
         self.setItem(r, 1, item)
         # precision
         item = QTableWidgetItem("%.4f" % obs["precision"])
         item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable)
         self.setItem(r, 2, item)
     self.adjustSize()
Exemple #46
0
    def addPlayer(self, player):
        r = self.rowCount()
        self.setRowCount(r + 1)
        name = player.name
        color = player.color
        name = QTableWidgetItem(name)
        name.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)

        colorItem = QTableWidgetItem()
        colorItem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        colorItem.setBackground(QColor(*color))

        cards = QTableWidgetItem()
        cards.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        cards.setTextAlignment(Qt.AlignCenter)
        cards.setData(Qt.DisplayRole, 0)

        troops = QTableWidgetItem()
        troops.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        troops.setTextAlignment(Qt.AlignCenter)
        troops.setData(Qt.DisplayRole, 0)

        territories = QTableWidgetItem()
        territories.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        territories.setTextAlignment(Qt.AlignCenter)
        territories.setData(Qt.DisplayRole, 0)

        troopsPerTurn = QTableWidgetItem()
        troopsPerTurn.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        troopsPerTurn.setTextAlignment(Qt.AlignCenter)
        troopsPerTurn.setData(Qt.DisplayRole, 0)

        self.setItem(r, self.Name, name)
        self.setItem(r, self.Color, colorItem)
        self.setItem(r, self.Cards, cards)
        self.setItem(r, self.NumberOfTroops, troops)
        self.setItem(r, self.NumberOfTerritories, territories)
        self.setItem(r, self.TroopsPerTurn, troopsPerTurn)
    def addAutoFieldToAutoFieldsTable(self,
                                      autoFieldId,
                                      autoField,
                                      freezeSorting=True):
        """ Add a whole row to the AutoFields table """
        if self.chkOnlyEnabledAutoFields.isChecked(
        ) and not autoField['enabled']:
            return

        if freezeSorting:
            self.tblAutoFields.setSortingEnabled(False)

        row = self.tblAutoFields.rowCount()
        self.tblAutoFields.insertRow(row)
        name = autoField['layer']
        if 'layerId' in autoField:
            lyr = QgsMapLayerRegistry.instance().mapLayer(autoField['layerId'])
            name = lyr.name()
        item = QTableWidgetItem(name)
        item.setData(Qt.UserRole, autoFieldId)
        item.setData(Qt.ToolTipRole, autoField['layer'])
        if not autoField['enabled']:
            item.setForeground(QBrush(Qt.gray))
        self.tblAutoFields.setItem(row, 0, item)
        item = QTableWidgetItem(autoField['field'])
        if not autoField['enabled']:
            item.setForeground(QBrush(Qt.gray))
        self.tblAutoFields.setItem(row, 1, item)
        item = QTableWidgetItem(autoField['expression'])
        if not autoField['enabled']:
            item.setForeground(QBrush(Qt.gray))
        self.tblAutoFields.setItem(row, 2, item)
        item = QTableWidgetItem(
            QApplication.translate("AutoFieldsDockWidgetPy", "Enabled"
                                   ) if autoField['enabled'] else QApplication.
            translate("AutoFieldsDockWidgetPy", "Disabled"))
        item.setData(Qt.UserRole,
                     'enabled' if autoField['enabled'] else 'disabled')
        if not autoField['enabled']:
            item.setForeground(QBrush(Qt.gray))
        self.tblAutoFields.setItem(row, 3, item)

        if freezeSorting:
            self.tblAutoFields.setSortingEnabled(True)
 def _reloadAnnotationTable(self):
     self.annotationTableWidget.clear()
     self.annotationTableWidget.setRowCount( len(self._annotations) )
     self._initAnnotationTableHeader()
     
     # Flip the key/value of the annotation list so we can sort them by label
     annotations = self._annotations.items()
     annotations = map( lambda (coord3d, (label,comment)): (label, coord3d, comment), annotations )
     annotations = sorted( annotations )
     
     for row, (ravelerLabel, coord3d, comment) in enumerate( annotations ):
         coordItem = QTableWidgetItem( "{}".format( coord3d ) )
         labelItem = QTableWidgetItem( "{}".format( ravelerLabel ) )
         commentItem = QTableWidgetItem( comment )
         
         coordItem.setData( Qt.UserRole, ( coord3d, ravelerLabel ) )
         labelItem.setData( Qt.UserRole, ( coord3d, ravelerLabel ) )
         commentItem.setData( Qt.UserRole, ( coord3d, ravelerLabel ) )
         
         self.annotationTableWidget.setItem( row, AnnotationTableColumns.Coordinates, coordItem )
         self.annotationTableWidget.setItem( row, AnnotationTableColumns.Body, labelItem )
         self.annotationTableWidget.setItem( row, AnnotationTableColumns.Comment, commentItem )
    def addAutoFieldToAutoFieldsTable( self, autoFieldId, autoField, freezeSorting=True ):
        """ Add a whole row to the AutoFields table """
        if self.chkOnlyEnabledAutoFields.isChecked() and not autoField['enabled']:
            return

        if freezeSorting:
            self.tblAutoFields.setSortingEnabled( False )

        row = self.tblAutoFields.rowCount()
        self.tblAutoFields.insertRow( row )
        name = autoField['layer']
        if 'layerId' in autoField:
            lyr = QgsMapLayerRegistry.instance().mapLayer( autoField['layerId'] )
            name = lyr.name()
        item = QTableWidgetItem( name )
        item.setData( Qt.UserRole, autoFieldId )
        item.setData( Qt.ToolTipRole, autoField['layer'] )
        if not autoField['enabled']:
            item.setForeground( QBrush( Qt.gray ) )
        self.tblAutoFields.setItem( row, 0, item )
        item = QTableWidgetItem( autoField['field'] )
        if not autoField['enabled']:
            item.setForeground( QBrush( Qt.gray ) )
        self.tblAutoFields.setItem( row, 1, item )
        item = QTableWidgetItem( autoField['expression'] )
        if not autoField['enabled']:
            item.setForeground( QBrush( Qt.gray ) )
        self.tblAutoFields.setItem( row, 2, item )
        item = QTableWidgetItem( QApplication.translate( "AutoFieldsDockWidgetPy",
            "Enabled" ) if autoField['enabled'] else QApplication.translate( "AutoFieldsDockWidgetPy", "Disabled" ) )
        item.setData( Qt.UserRole, 'enabled' if autoField['enabled'] else 'disabled' )
        if not autoField['enabled']:
            item.setForeground( QBrush( Qt.gray ) )
        self.tblAutoFields.setItem( row, 3, item )

        if freezeSorting:
            self.tblAutoFields.setSortingEnabled( True )
Exemple #50
0
 def addLayer(self, layer, headers, types, features):
     tab = QtGui.QWidget()
     tab.layer = layer
     p1_vertical = QtGui.QVBoxLayout(tab)
     p1_vertical.setContentsMargins(0,0,0,0)
     
     table = QtGui.QTableWidget();
     self.connect(table, SIGNAL("itemSelectionChanged()"), self.selectionChanged)
     table.title = layer.name()
     table.crs = layer.crs()
     table.setColumnCount(len(headers))
     if len(features) > 0:
         table.setRowCount(len(features))
         nbrow = len(features)
         self.loadingWindow.show()
         self.loadingWindow.setLabelText(table.title)
         self.loadingWindow.activateWindow();
         self.loadingWindow.showNormal();
         
         # Table population
         m = 0
         for feature in features:
             n = 0
             for cell in feature.attributes():
                 item = QTableWidgetItem()
                 item.setData(Qt.DisplayRole, cell)
                 item.setFlags(item.flags() ^ Qt.ItemIsEditable)
                 item.feature = feature
                 table.setItem(m, n, item)
                 n += 1
             m += 1
             self.loadingWindow.setValue(int((float(m)/nbrow)*100))  
             QApplication.processEvents()
         
     else:
         table.setRowCount(0)  
                         
     table.setHorizontalHeaderLabels(headers)
     table.horizontalHeader().setMovable(True)
     
     table.types = types
     table.filter_op = []
     table.filters = []
     for i in range(0, len(headers)):
         table.filters.append('')
         table.filter_op.append(0)
     
     header = table.horizontalHeader()
     header.setContextMenuPolicy(Qt.CustomContextMenu)
     header.customContextMenuRequested.connect(partial(self.filterMenu, table))
         
     table.setSortingEnabled(True)
     
     p1_vertical.addWidget(table)
     
     # Status bar to display informations (ie: area)
     tab.sb = QtGui.QStatusBar()
     p1_vertical.addWidget(tab.sb)
     
     title = table.title
     # We reduce the title's length to 20 characters
     if len(title)>20:
         title = title[:20]+'...'
     
     # We add the number of elements to the tab's title.
     title += ' ('+str(len(features))+')'
         
     self.tabWidget.addTab(tab, title) # Add the tab to the conatiner
     self.tabWidget.setTabToolTip(self.tabWidget.indexOf(tab), table.title) # Display a tooltip with the layer's full name
    def populateLayerTable( self ):
        """
        Fill the table for a given layer type
        """
        # Get parameters for the widget
        lt = self.layersTable
        table = lt['tableWidget']

        attributes = lt['attributes']

        headerData = [ a['key'] for a in attributes ]

        # empty previous content
        for row in range(table.rowCount()):
            table.removeRow(row)
        table.setRowCount(0)

        # create columns and header row
        columns = [ a['key'] for a in attributes ]
        colCount = len( columns )
        table.setColumnCount( colCount )
        table.setHorizontalHeaderLabels( tuple( columns ) )

        # load content from project layers
        lr = QgsMapLayerRegistry.instance()
        for lid in lr.mapLayers():
            layer = lr.mapLayer( lid )

            lineData = []

            # Set row and column count
            twRowCount = table.rowCount()
            # add a new line
            table.setRowCount( twRowCount + 1 )
            table.setColumnCount( colCount )
            i=0

            if layer.customProperty('dynamicDatasourceActive') == 'True':
                bg = QColor(175, 208, 126)
            else:
                bg = Qt.transparent

            # get information
            for attr in attributes:
                newItem = QTableWidgetItem( )

                # Is editable or not
                if( attr['editable'] ):
                    newItem.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled )
                else:
                    newItem.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled  )

                # background
                newItem.setBackground( bg )

                # Item value
                value = self.getLayerProperty( layer, attr['key'] )
                newItem.setData( Qt.EditRole, value )

                # Add cell data to lineData
                # encode it in the file system encoding, only if needed
                if hasattr( value, 'encode' ):
                    value = value.encode( sys.getfilesystemencoding() )
                lineData.append( value )

                # Add item
                table.setItem(twRowCount, i, newItem)
                i+=1
Exemple #52
0
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):
        app.exec_()
 def setData(self,role,value):
     QTableWidgetItem.setData(role,value)
     if(role == Qt.EditRole):
         self.setDirty()
 def addItem(r, c, text, tip = None):
     item = QTableWidgetItem(text)
     if tip:
         item.setToolTip(tip)
     item.setData(ACTION_ROLE, QVariant(r))
     self._settingsTable.setItem(r, c, item)
Exemple #55
0
    def __init__(self, bpms, cors, parent = None):
        super(OrbitCorrGeneral, self).__init__(parent)

        self.bpms, self.cors = bpms, cors
        self.sb = [bpm.sb for bpm in self.bpms]
        self.x0, self.y0 = None, None
        self._update_current_orbit()

        self.table = QTableWidget(len(self.bpms), 9)
        self.table.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        hdview = QHeaderView(Qt.Horizontal)
        self.table.setHorizontalHeaderLabels(
            ['BPM Name', 's', "Beta X", "Beta Y",
             "Eta X", 'X Bump', 'Y Bump', "Target X", "Target Y"])
        self._twiss = getTwiss([b.name for b in self.bpms],
                               ["s", "betax", "betay", "etax"])
        for i,bpm in enumerate(self.bpms):
            it = QTableWidgetItem(bpm.name)
            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            self.table.setItem(i, 0, it)

            it = QTableWidgetItem(str(bpm.sb))
            it.setFlags(it.flags() & (~Qt.ItemIsEditable))
            #it.setMinimumWidth(80)
            self.table.setItem(i, 1, it)
            self.table.setItem(i, 2,
                               QTableWidgetItem("%.4f" % self._twiss[i,1]))
            self.table.setItem(i, 3,
                               QTableWidgetItem("%.4f" % self._twiss[i,2]))
            self.table.setItem(i, 4,
                               QTableWidgetItem("%.4f" % self._twiss[i,3]))

            for j in range(5, 9):
                it = QTableWidgetItem(str(0.0))
                it.setData(Qt.DisplayRole, str(0.0))
                it.setFlags(it.flags() | Qt.ItemIsEditable)
                self.table.setItem(i, j, it) 
            # use the current orbit 
            #self.table.item(i,4).setData(Qt.DisplayRole, str(self.x0[i]))
            #self.table.item(i,5).setData(Qt.DisplayRole, str(self.y0[i]))

        #self.connect(self.table, SIGNAL("cellClicked(int, int)"),
        #             self._cell_clicked)
        self.table.resizeColumnsToContents()
        #self.table.horizontalHeader().setStretchLastSection(True)
        #for i in range(4):
        #    print "width", i, self.table.columnWidth(i)
        #self.table.setColumnWidth(0, 300)
        self.table.setColumnWidth(1, 80)

        vbox1 = QtGui.QVBoxLayout()
        frmbox = QFormLayout()
        self.base_orbit_box = QtGui.QComboBox()
        #self.base_orbit_box.addItems([
        #        "Current Orbit", "All Zeros"])
        self.base_orbit_box.addItems(["All Zeros", "Current Orbit"])
        frmbox.addRow("Orbit Base", self.base_orbit_box)
        grp = QtGui.QGroupBox("Local Bump")
        grp.setLayout(frmbox)
        vbox1.addWidget(grp)

        frmbox = QFormLayout()
        hln1 = QtGui.QFrame()
        hln1.setLineWidth(3)
        hln1.setFrameStyle(QtGui.QFrame.Sunken)
        hln1.setFrameShape(QtGui.QFrame.HLine)
        frmbox.addRow(hln1)
        self.repeatbox = QSpinBox()
        self.repeatbox.setRange(1, 20)
        self.repeatbox.setValue(3)
        # or connect the returnPressed() signal
        frmbox.addRow("&Repeat correction", self.repeatbox)

        self.rcondbox = QLineEdit()
        self.rcondbox.setValidator(QDoubleValidator(0, 1, 0, self))
        self.rcondbox.setText("1e-2")
        frmbox.addRow("r&cond for SVD", self.rcondbox)

        self.scalebox = QDoubleSpinBox()
        self.scalebox.setRange(0.01, 5.00)
        self.scalebox.setSingleStep(0.01)
        self.scalebox.setValue(0.68)
        frmbox.addRow("&Scale correctors", self.scalebox)

        #hln2 = QtGui.QFrame()
        #hln2.setLineWidth(3)
        #hln2.setFrameStyle(QtGui.QFrame.Sunken)
        #hln2.setFrameShape(QtGui.QFrame.HLine)
        #frmbox.addRow(hln2)

        self.progress = QProgressBar()
        self.progress.setMaximum(self.repeatbox.value())
        self.progress.setMaximumHeight(15)
        frmbox.addRow("Progress", self.progress)
        grp = QtGui.QGroupBox("Correction")
        grp.setLayout(frmbox)
        vbox1.addWidget(grp)

        #vbox.addStretch(1.0)
        #self.qdb = QDialogButtonBox(self)
        #self.qdb.addButton("APP", QDialogButtonBox.ApplyRole)
        #self.qdb.addButton("R", QDialogButtonBox.ResetRole)
        #btn.setDefault(True)
        #self.qdb.addButton(QDialogButtonBox.Cancel)
        #self.qdb.addButton(QDialogButtonBox.Help)

        gbox = QtGui.QGridLayout()
        btn = QPushButton("Clear")
        self.connect(btn, SIGNAL("clicked()"), self.resetBumps)
        gbox.addWidget(btn, 0, 1)
        self.correctOrbitBtn = QPushButton("Apply")
        #self.correctOrbitBtn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.correctOrbitBtn.setStyleSheet("QPushButton:disabled { color: gray }");
        self.connect(self.correctOrbitBtn, SIGNAL("clicked()"), self.call_apply)
        self.correctOrbitBtn.setDefault(True)
        gbox.addWidget(self.correctOrbitBtn, 1, 1)
        gbox.setColumnStretch(0, 1)

        vbox1.addStretch()
        vbox1.addLayout(gbox)
        
        hbox1 = QtGui.QHBoxLayout()
        hbox1.addWidget(self.table, 2)
        hbox1.addLayout(vbox1, 0)
        self.setLayout(hbox1)

        self.connect(self.base_orbit_box,
                     SIGNAL("currentIndexChanged(QString)"), 
                     self.updateTargetOrbit)
        self.connect(self.repeatbox, SIGNAL("valueChanged(int)"),
                     self.progress.setMaximum)
        self.connect(self.table, SIGNAL("cellChanged (int, int)"),
                     self.updateBump)