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()
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
def _add_task_to_table(self, row, task): self._ignore_cell_changed = True self.setItem(row, self._dict_header['id'], QTableWidgetItem(str(task.identifier))) self.item(row, self._dict_header['id']) \ .setTextAlignment(Qt.AlignCenter) self.setItem(row, self._dict_header['name'], QTableWidgetItem(str(task.name))) combo = QComboBox() items = [task_type for task_type in Task.task_types_names] combo.addItems(items) # FIXME: only until I get an access to the documentation. for i, t in enumerate(Task.task_types_names): if t == task.task_type: combo.setCurrentIndex(i) combo.currentIndexChanged.connect( lambda x: self._cell_changed(row, self._dict_header['task_type'])) self.setCellWidget(row, self._dict_header['task_type'], combo) item = QTableWidgetItem(task.abort_on_miss and 'Yes' or 'No') item.setFlags( Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsSelectable) item.setCheckState(task.abort_on_miss and Qt.Checked or Qt.Unchecked) self.setItem(row, self._dict_header['abort'], item) self.setItem(row, self._dict_header['list_activation_dates'], QTableWidgetItem( ', '.join(map(str, task.list_activation_dates)))) self.item(row, self._dict_header['list_activation_dates']) \ .setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) for i in ['activation_date', 'period', 'deadline', 'wcet', 'base_cpi', 'n_instr', 'mix', 'acet', 'et_stddev', 'preemption_cost']: self.setItem(row, self._dict_header[i], QTableWidgetItem(str(task.__dict__[i]))) self.item(row, self._dict_header[i]) \ .setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) stack_item = QTableWidgetItem(str(task.stack_file)) stack_item.setFlags(stack_item.flags() ^ (Qt.ItemIsEditable)) self.setItem(row, self._dict_header['sdp'], stack_item) combo = QComboBox() combo.currentIndexChanged.connect( lambda x: self._cell_changed(row, self._dict_header['followed'])) self.setCellWidget(row, self._dict_header['followed'], combo) for col in range(len(self._custom_fields)): key = self._custom_fields[col] if key in task.data and task.data[key] is not None: item = QTableWidgetItem(str(task.data[key])) else: item = QTableWidgetItem('') item.setBackgroundColor(QColor.fromRgb(200, 255, 200)) self.setItem(row, col + len(self._header), item) self._ignore_cell_changed = False self._show_period(task, row)
def updatePackages(self): library_ = robjects.r.get('library', mode='function') packages_ = robjects.r.get('.packages', mode='function') loaded = list(packages_()) packages = list(library_()[1]) length = len(packages) self.packageTable.clearContents() #self.table.setRowCount(length/3) packageList = [] for i in range(length/3): package = unicode(packages[i]) if not package in packageList: packageList.append(package) self.packageTable.setRowCount(len(packageList)) item = QTableWidgetItem("Loaded") item.setFlags( Qt.ItemIsUserCheckable|Qt.ItemIsEnabled|Qt.ItemIsSelectable) if package in loaded: item.setCheckState(Qt.Checked) else: item.setCheckState(Qt.Unchecked) self.packageTable.setItem(i, 0, item) item = QTableWidgetItem(unicode(packages[i])) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable) self.packageTable.setItem(i, 1, item) item = QTableWidgetItem(unicode(packages[i+(2*(length/3))])) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable) self.packageTable.setItem(i, 2, item) item = QTableWidgetItem(unicode(packages[i+(length/3)])) item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable) self.packageTable.setItem(i, 3, item) self.packageTable.resizeColumnsToContents()
def create_table_widget(table, parent): formats = table.getColFormats() names = table.getColNames() indices_of_visible_columns = [j for (j, f) in enumerate(formats) if f is not None] headers = ["ok"] + [names[j] for j in indices_of_visible_columns] n_rows = len(table) widget = QTableWidget(n_rows, 1 + len(indices_of_visible_columns), parent=parent) widget.setHorizontalHeaderLabels(headers) widget.setMinimumSize(200, 200) widget.horizontalHeader().setResizeMode(QHeaderView.Interactive) for i, row in enumerate(table.rows): item = QTableWidgetItem() item.setCheckState(Qt.Unchecked) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable) widget.setItem(i, 0, item) for j0, j in enumerate(indices_of_visible_columns): value = row[j] formatter = table.colFormatters[j] item = QTableWidgetItem(formatter(value)) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) widget.setItem(i, j0 + 1, item) return widget
def create_table_widget(table, parent): formats = table.getColFormats() names = table.getColNames() indices_of_visible_columns = [ j for (j, f) in enumerate(formats) if f is not None ] headers = ["ok"] + [names[j] for j in indices_of_visible_columns] n_rows = len(table) widget = QTableWidget(n_rows, 1 + len(indices_of_visible_columns), parent=parent) widget.setHorizontalHeaderLabels(headers) widget.setMinimumSize(200, 200) widget.horizontalHeader().setResizeMode(QHeaderView.Interactive) for i, row in enumerate(table.rows): item = QTableWidgetItem() item.setCheckState(Qt.Unchecked) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable) widget.setItem(i, 0, item) for j0, j in enumerate(indices_of_visible_columns): value = row[j] formatter = table.colFormatters[j] item = QTableWidgetItem(formatter(value)) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) widget.setItem(i, j0 + 1, item) return widget
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)
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 render_result(self): query = self.query_edit.text() if not query: return self.feed = FeedBooks() response = self.feed.search(str(query)) if not response: QMessageBox.critical(self, 'Error', 'Could not get any result') return self.table.clear() self.table.setHorizontalHeaderLabels(['Select', 'Title', 'URL']) self.table.setRowCount(len(response[1])) for i, name in enumerate(zip(response[1], response[3])): item = QTableWidgetItem(1) item.data(Qt.CheckStateRole) item.setCheckState(Qt.Checked) self.table.setItem(i, 0, item) for j in range(2): item = QTableWidgetItem(name[j]) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.table.setItem(i, j+1, item) self.table.resizeColumnsToContents()
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 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()
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
def _add_task_to_table(self, row, task): self._ignore_cell_changed = True self.setItem(row, self._dict_header['id'], QTableWidgetItem(str(task.identifier))) self.item(row, self._dict_header['id']) \ .setTextAlignment(Qt.AlignCenter) self.setItem(row, self._dict_header['name'], QTableWidgetItem(str(task.name))) combo = QComboBox() items = [task_type for task_type in Task.task_types_names] combo.addItems(items) combo.setCurrentIndex(combo.findText(task.task_type)) combo.currentIndexChanged.connect( lambda x: self._cell_changed(row, self._dict_header['task_type'])) self.setCellWidget(row, self._dict_header['task_type'], combo) item = QTableWidgetItem(task.abort_on_miss and 'Yes' or 'No') item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsSelectable) item.setCheckState(task.abort_on_miss and Qt.Checked or Qt.Unchecked) self.setItem(row, self._dict_header['abort'], item) self.setItem( row, self._dict_header['list_activation_dates'], QTableWidgetItem(', '.join(map(str, task.list_activation_dates)))) self.item(row, self._dict_header['list_activation_dates']) \ .setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) for i in [ 'activation_date', 'period', 'deadline', 'wcet', 'base_cpi', 'n_instr', 'mix', 'acet', 'et_stddev', 'preemption_cost' ]: self.setItem(row, self._dict_header[i], QTableWidgetItem(str(task.__dict__[i]))) self.item(row, self._dict_header[i]) \ .setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) stack_item = QTableWidgetItem(str(task.stack_file)) stack_item.setFlags(stack_item.flags() ^ (Qt.ItemIsEditable)) self.setItem(row, self._dict_header['sdp'], stack_item) combo = QComboBox() combo.currentIndexChanged.connect( lambda x: self._cell_changed(row, self._dict_header['followed'])) self.setCellWidget(row, self._dict_header['followed'], combo) for col in range(len(self._custom_fields)): key = self._custom_fields[col] if key in task.data and task.data[key] is not None: item = QTableWidgetItem(str(task.data[key])) else: item = QTableWidgetItem('') item.setBackgroundColor(QColor.fromRgb(200, 255, 200)) self.setItem(row, col + len(self._header), item) self._ignore_cell_changed = False self._show_period(task, row)
def initWithExtents(self, axes, shape, start, stop): self.setColumnCount(3) self.setHorizontalHeaderLabels(["range", "[start,", "stop)"]) self.resizeColumnsToContents() tagged_shape = collections.OrderedDict(zip(axes, shape)) tagged_start = collections.OrderedDict(zip(axes, start)) tagged_stop = collections.OrderedDict(zip(axes, stop)) self._tagged_shape = tagged_shape self.setRowCount(len(tagged_shape)) self.setVerticalHeaderLabels(tagged_shape.keys()) self._boxes.clear() for row, (axis_key, extent) in enumerate(tagged_shape.items()): # Init 'full' checkbox checkbox_item = QTableWidgetItem("All") if tagged_start[axis_key] is None: checkbox_item.setCheckState(Qt.Checked) else: checkbox_item.setCheckState(Qt.Unchecked) checkbox_item.setFlags( Qt.ItemFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)) self.setItem(row, 0, checkbox_item) # Init min/max spinboxes default_start = tagged_start[axis_key] or 0 default_stop = tagged_stop[axis_key] or extent or DEFAULT_MAX_EXTENT extent = extent or DEFAULT_MAX_EXTENT startBox = RoiSpinBox(self, 0, extent - 1, 0) stopBox = RoiSpinBox(self, 1, extent, extent) startBox.setPartner(stopBox) stopBox.setPartner(startBox) startBox.setEnabled(tagged_start[axis_key] is not None) stopBox.setEnabled(tagged_stop[axis_key] is not None) if startBox.isEnabled(): startBox.setValue(default_start) if stopBox.isEnabled(): stopBox.setValue(default_stop) startBox.valueChanged.connect(self._updateRoi) stopBox.valueChanged.connect(self._updateRoi) self.setCellWidget(row, 1, startBox) self.setCellWidget(row, 2, stopBox) self._boxes[axis_key] = (checkbox_item, startBox, stopBox) self._updateRoi() self.resizeColumnsToContents()
def populate(self, modules): i = 0 for k, v in modules.iteritems(): item = QTableWidgetItem(str(k)) item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) item.setCheckState(Qt.Checked) itemv = QTableWidgetItem(str(v)) itemv.setFlags(Qt.ItemIsEnabled) self.setItem(i, 0, item) self.setItem(i, 1, itemv) i += 1
def initWithExtents(self, axes, shape, start, stop): self.setColumnCount( 3 ) self.setHorizontalHeaderLabels(["range", "[start,", "stop)"]) self.resizeColumnsToContents() tagged_shape = collections.OrderedDict( zip(axes, shape) ) tagged_start = collections.OrderedDict( zip(axes, start) ) tagged_stop = collections.OrderedDict( zip(axes, stop) ) self._tagged_shape = tagged_shape self.setRowCount( len(tagged_shape) ) self.setVerticalHeaderLabels( tagged_shape.keys() ) self._boxes.clear() for row, (axis_key, extent) in enumerate(tagged_shape.items()): # Init 'full' checkbox checkbox_item = QTableWidgetItem("All") if tagged_start[axis_key] is None: checkbox_item.setCheckState( Qt.Checked ) else: checkbox_item.setCheckState( Qt.Unchecked ) checkbox_item.setFlags( Qt.ItemFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) ) self.setItem(row, 0, checkbox_item) # Init min/max spinboxes default_start = tagged_start[axis_key] or 0 default_stop = tagged_stop[axis_key] or extent or DEFAULT_MAX_EXTENT extent = extent or DEFAULT_MAX_EXTENT startBox = RoiSpinBox(self, 0, extent-1, 0 ) stopBox = RoiSpinBox(self, 1, extent, extent ) startBox.setPartner( stopBox ) stopBox.setPartner( startBox ) startBox.setEnabled( tagged_start[axis_key] is not None ) stopBox.setEnabled( tagged_stop[axis_key] is not None ) if startBox.isEnabled(): startBox.setValue( default_start ) if stopBox.isEnabled(): stopBox.setValue( default_stop ) startBox.valueChanged.connect( self._updateRoi ) stopBox.valueChanged.connect( self._updateRoi ) self.setCellWidget( row, 1, startBox ) self.setCellWidget( row, 2, stopBox ) self._boxes[axis_key] = (checkbox_item, startBox, stopBox) self._updateRoi() self.resizeColumnsToContents()
def load(self, error=True): s = QSettings("norBIT", "norGIS-ALKIS-Erweiterung") s.setValue("service", self.leSERVICE.text()) s.setValue("host", self.leHOST.text()) s.setValue("port", self.lePORT.text()) s.setValue("dbname", self.leDBNAME.text()) s.setValue("uid", self.leUID.text()) s.setValue("pwd", self.lePWD.text()) modelle = s.value("modellarten", ['DLKM', 'DKKM1000']) (db, conninfo) = self.plugin.opendb() if db: qry = QSqlQuery(db) if qry.exec_(""" SELECT modell,count(*) FROM ( SELECT unnest(modell) AS modell FROM po_points UNION ALL SELECT unnest(modell) AS modell FROM po_lines UNION ALL SELECT unnest(modell) AS modell FROM po_polygons UNION ALL SELECT unnest(modell) AS modell from po_lines UNION ALL SELECT unnest(modell) AS modell from po_labels ) AS foo GROUP BY modell ORDER BY count(*) DESC """): self.twModellarten.clearContents() res = {} while qry.next(): res[qry.value(0)] = qry.value(1) self.twModellarten.setRowCount(len(res)) i = 0 for k, n in sorted(res.iteritems(), key=operator.itemgetter(1), reverse=True): item = QTableWidgetItem(k) item.setCheckState(Qt.Checked if ( item.text() in modelle) else Qt.Unchecked) self.twModellarten.setItem(i, 0, item) item = QTableWidgetItem(str(n)) self.twModellarten.setItem(i, 1, item) i += 1 self.twModellarten.resizeColumnsToContents() elif error: modelle = [] self.twModellarten.clearContents() self.twModellarten.setDisabled(True) else: modelle = [] elif error: QMessageBox.critical(None, "ALKIS", u"Datenbankverbindung schlug fehl.")
def populateList(self): dicts = self.manager.dictionnaries() currow = 0 for _dict in dicts.iterkeys(): self.dicos.setRowCount(currow + 1) item = QTableWidgetItem(QString.fromUtf8(dicts[_dict].fileName())) item.setFlags(Qt.ItemIsUserCheckable|Qt.ItemIsEnabled|Qt.ItemIsSelectable) item.setCheckState(Qt.Unchecked) self.dicos.setItem(currow, 0, item) name = QTableWidgetItem(QString.fromUtf8(_dict)) name.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable) self.dicos.setItem(currow, 1, name) currow += 1
def __init__(self, parent): QDialog.__init__(self, parent) # Set up the user interface from Designer. self.ui = ui = Ui_SettingsDialog() ui.setupUi(self) ui.lineEdit_BrowserPath.setPlaceholderText( "Leave this empty to use your default browser") ui.toolButton_Browse.clicked.connect(self.browseClicked) # load settings settings = QSettings() ui.lineEdit_BrowserPath.setText( settings.value("/Qgis2threejs/browser", "", type=unicode)) enabled_plugins = QSettings().value("/Qgis2threejs/plugins", "", type=unicode).split(",") # initialize plugin table widget plugin_dir = QDir( os.path.join(os.path.dirname(QFile.decodeName(__file__)), "plugins")) plugins = plugin_dir.entryList(QDir.Dirs | QDir.NoSymLinks | QDir.NoDotAndDotDot) tableWidget = ui.tableWidget_Plugins tableWidget.setRowCount(len(plugins)) tableWidget.setColumnCount(1) tableWidget.setHorizontalHeaderLabels(["Name"]) tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) headerView = tableWidget.horizontalHeader() headerView.setResizeMode(0, QHeaderView.Stretch) self.plugin_metadata = [] for i, name in enumerate(plugins): parser = ConfigParser.SafeConfigParser() with codecs.open( os.path.join(plugin_dir.absoluteFilePath(name), "metadata.txt"), "r", "UTF-8") as f: parser.readfp(f) metadata = dict(parser.items("general")) self.plugin_metadata.append(metadata) item = QTableWidgetItem(metadata.get("name", name)) item.setCheckState(Qt.Checked if name in enabled_plugins else Qt.Unchecked) tableWidget.setItem(i, 0, item) tableWidget.selectionModel().currentRowChanged.connect( self.pluginSelectionChanged)
def load(self, error=True): s = QSettings( "norBIT", "norGIS-ALKIS-Erweiterung" ) s.setValue( "service", self.leSERVICE.text() ) s.setValue( "host", self.leHOST.text() ) s.setValue( "port", self.lePORT.text() ) s.setValue( "dbname", self.leDBNAME.text() ) s.setValue( "uid", self.leUID.text() ) s.setValue( "pwd", self.lePWD.text() ) modelle = s.value( "modellarten", ['DLKM','DKKM1000'] ) (db,conninfo) = self.plugin.opendb() if db: qry = QSqlQuery(db) if qry.exec_( """ SELECT modell,count(*) FROM ( SELECT unnest(modell) AS modell FROM po_points UNION ALL SELECT unnest(modell) AS modell FROM po_lines UNION ALL SELECT unnest(modell) AS modell FROM po_polygons UNION ALL SELECT unnest(modell) AS modell from po_lines UNION ALL SELECT unnest(modell) AS modell from po_labels ) AS foo GROUP BY modell ORDER BY count(*) DESC """ ): self.twModellarten.clearContents() res = {} while qry.next(): res[ qry.value(0) ] = qry.value(1) self.twModellarten.setRowCount( len(res) ) i = 0 for k,n in sorted(res.iteritems(), key=operator.itemgetter(1), reverse=True): item = QTableWidgetItem( k ) item.setCheckState( Qt.Checked if (item.text() in modelle) else Qt.Unchecked ) self.twModellarten.setItem( i, 0, item ) item = QTableWidgetItem( str(n) ) self.twModellarten.setItem( i, 1, item ) i += 1 self.twModellarten.resizeColumnsToContents() elif error: modelle = [] self.twModellarten.clearContents() self.twModellarten.setDisabled( True ) else: modelle = [] elif error: QMessageBox.critical( None, "ALKIS", u"Datenbankverbindung schlug fehl." )
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.setCheckState(Qt.Unchecked) else: item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
def do_add(self): #print "do_add() \n" row = self.tableWidget.rowCount() self.tableWidget.setRowCount(row + 1) #ckBox = QTableWidgetItem("select %d" %row) ckBox = QTableWidgetItem("Active") ckBox.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) ckBox.setCheckState(QtCore.Qt.Unchecked) self.tableWidget.setItem(row, 0, ckBox) cbBox = QtGui.QComboBox() cbBox.addItem("dnw") cbBox.addItem("fastboot") self.tableWidget.setCellWidget(row, 1, cbBox) self.tableWidget.setItem(row, 2, QTableWidgetItem(QString("0x00000000"))) self.tableWidget.setItem(row, 3, QTableWidgetItem(QString("./uboot.bin")))
def set_data(skins, table): table.setHorizontalHeaderLabels(['Name', 'URL']) table.horizontalHeader().setStretchLastSection(True) table.setSelectionBehavior(QAbstractItemView.SelectRows) for i in xrange(table.rowCount()): table.removeRow(0) r = 0 for skin in skins: table.insertRow(r) #Column 1 item = QTableWidgetItem(skin[1]) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) table.setItem(r, 1, item) #Column 0 item = QTableWidgetItem(skin[0]) table.setItem(r, 0, item) item.setCheckState(Qt.Unchecked) r += 1
def addSettingsToRow(settings, out_table): s = settings row = out_table.rowCount() out_table.insertRow(row) s = settings # insert values for i, value in enumerate([ s.layerName, s.startTimeAttribute, s.endTimeAttribute, s.isEnabled, s.layerId, s.timeFormat, str(s.offset), s.interpolationEnabled, s.idAttribute, s.interpolationMode, not s.geometriesCount, s.accumulate ]): item = QTableWidgetItem() if type(value) != bool: item.setText(value) else: item.setCheckState(Qt.Checked if value else Qt.Unchecked) out_table.setItem(row, i, item)
def initWithExtents(self, axes, shape, start, stop): tagged_shape = collections.OrderedDict(zip(axes, shape)) tagged_start = collections.OrderedDict(zip(axes, start)) tagged_stop = collections.OrderedDict(zip(axes, stop)) self._tagged_shape = tagged_shape self.setRowCount(len(tagged_shape)) self.setVerticalHeaderLabels(tagged_shape.keys()) for row, (axis_key, extent) in enumerate(tagged_shape.items()): # Init 'full' checkbox checkbox_item = QTableWidgetItem("All") if tagged_start[axis_key] is None: checkbox_item.setCheckState(Qt.Checked) else: checkbox_item.setCheckState(Qt.Unchecked) checkbox_item.setFlags( Qt.ItemFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)) self.setItem(row, 0, checkbox_item) # Init min/max spinboxes default_start = tagged_start[axis_key] or 0 default_stop = tagged_stop[axis_key] or extent startBox = RoiSpinBox(self, 0, extent - 1, default_start) stopBox = RoiSpinBox(self, 1, extent, default_stop) startBox.setPartner(stopBox) stopBox.setPartner(startBox) startBox.setValue(default_start) stopBox.setValue(default_stop) startBox.setEnabled(tagged_start[axis_key] is not None) stopBox.setEnabled(tagged_stop[axis_key] is not None) startBox.valueChanged.connect(self._updateRoi) stopBox.valueChanged.connect(self._updateRoi) self.setCellWidget(row, 1, startBox) self.setCellWidget(row, 2, stopBox) self._boxes[axis_key] = (checkbox_item, startBox, stopBox)
def initWithExtents(self, axes, shape, start, stop): tagged_shape = collections.OrderedDict( zip(axes, shape) ) tagged_start = collections.OrderedDict( zip(axes, start) ) tagged_stop = collections.OrderedDict( zip(axes, stop) ) self._tagged_shape = tagged_shape self.setRowCount( len(tagged_shape) ) self.setVerticalHeaderLabels( tagged_shape.keys() ) for row, (axis_key, extent) in enumerate(tagged_shape.items()): # Init 'full' checkbox checkbox_item = QTableWidgetItem("All") if tagged_start[axis_key] is None: checkbox_item.setCheckState( Qt.Checked ) else: checkbox_item.setCheckState( Qt.Unchecked ) checkbox_item.setFlags( Qt.ItemFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) ) self.setItem(row, 0, checkbox_item) # Init min/max spinboxes default_start = tagged_start[axis_key] or 0 default_stop = tagged_stop[axis_key] or extent startBox = RoiSpinBox(self, 0, extent-1, default_start ) stopBox = RoiSpinBox(self, 1, extent, default_stop ) startBox.setPartner( stopBox ) stopBox.setPartner( startBox ) startBox.setValue( default_start ) stopBox.setValue( default_stop ) startBox.setEnabled( tagged_start[axis_key] is not None ) stopBox.setEnabled( tagged_stop[axis_key] is not None ) startBox.valueChanged.connect( self._updateRoi ) stopBox.valueChanged.connect( self._updateRoi ) self.setCellWidget( row, 1, startBox ) self.setCellWidget( row, 2, stopBox ) self._boxes[axis_key] = (checkbox_item, startBox, stopBox)
def do_additem(self, cmd, args, filename): row = self.tableWidget.rowCount() self.tableWidget.setRowCount(row + 1) #ckBox = QTableWidgetItem("select %d" %row) ckBox = QTableWidgetItem("Active") ckBox.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) ckBox.setCheckState(QtCore.Qt.Unchecked) self.tableWidget.setItem(row, 0, ckBox) cbBox = QtGui.QComboBox() cbBox.addItem("dnw") cbBox.addItem("fastboot") if cmd == "fastboot": cbBox.setCurrentIndex(1) else: cbBox.setCurrentIndex(0) self.tableWidget.setCellWidget(row, 1, cbBox) self.tableWidget.setItem(row, 2, QTableWidgetItem(QString(args))) self.tableWidget.setItem(row, 3, QTableWidgetItem(QString(filename)))
def create_widgets(self): # main/delete/supergroup self.set_as_main_button = QPushButton("Set As Main") self.create_super_group_button = QPushButton("Create Super Group") self.delete_groups_button = QPushButton("Delete Groups") self.revert_groups_button = QPushButton("Revert Groups") self.show_groups_button = QPushButton("Show Groups") self.hide_groups_button = QPushButton("Hide Groups") # closing self.apply_button = QPushButton("Apply") self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Cancel") #table self.table = QTableWidget() self.checks = [] self.names_text = [] bold = QtGui.QFont() bold.setBold(True) bold.setItalic(True) bold.setWeight(75) anames = array(self.names) for iname, name in enumerate(anames[self.inames]): check = QTableWidgetItem() check.setCheckState(False) # TODO: create right click menu ??? name_text = QTableWidgetItem(str(name)) if iname == self.imain: name_text.setFont(bold) self.shown_set.add(iname) check.setCheckState(2) name_text.setBackground(QtGui.QColor(*self.light_grey)) elif iname in self.shown_set: name_text.setBackground(QtGui.QColor(*self.light_grey)) self.checks.append(check) self.names_text.append(name_text)
def addDictionnary(self): fn = QFileDialog.getOpenFileName(self, self.tr("Select your dictionnary"), os.path.expanduser('~')) if fn != "": ufn = str(unicode(fn).encode('utf-8')) dicname = self.autoDicName(ufn) if dicname != None: currow = self.dicos.rowCount() self.dicos.setRowCount(currow + 1) item = QTableWidgetItem(QString.fromUtf8(ufn)) item.setFlags(Qt.ItemIsUserCheckable|Qt.ItemIsEnabled|Qt.ItemIsSelectable) item.setCheckState(Qt.Unchecked) self.dicos.setItem(currow, 0, item) name = QTableWidgetItem(QString.fromUtf8(dicname)) name.setFlags(Qt.ItemIsEnabled|Qt.ItemIsSelectable) self.dicos.setItem(currow, 1, name) dict_ = FileDictionnary(ufn) dict_.thisown = False try: self.manager.add(dicname, dict_) except RuntimeError: print "Error adding new dictionnary"
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() 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') enabledItem.setCheckState(Qt.Checked) enabledItem.setFlags(enabledItem.flags() & Qt.ItemIsEditable) ODKfieldItem.setFlags(ODKfieldItem.flags() & Qt.ItemIsEditable) QGISfieldItem.setFlags(QGISfieldItem.flags() & Qt.ItemIsEditable)
def onRemoveClicked(self): if len(self.removeList) == 0: QMessageBox.information(self, 'Remove Sentences', 'Select the Sentences to Delete') else: reply = QMessageBox.question(self, 'Remove Sentences', 'You want to delete the selected sentences', QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.Yes: for sentence in self.removeList: if sentence in self.sentenceList: self.sentenceList.remove(sentence) ## clear the contents of the Table self.sentenceTable.clearContents() cellList = [] ## Add the new entries into the table 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() for index in range(0, len(self.sentenceList)): self.sentenceTable.setItem(index, self.col, cellList.pop()) self.sentenceTable.setRowCount(len(self.sentenceList)) deleteSentences = [] for sentence in self.removeList.values(): deleteSentences.append(sentence) rowsDeletec = data.Data().deleteSentencesFromDatabase(deleteSentences) self.getSentencesFromDatabase() self.removeList = {}
def __init__(self, parent): QDialog.__init__(self, parent) # Set up the user interface from Designer. self.ui = ui = Ui_SettingsDialog() ui.setupUi(self) ui.lineEdit_BrowserPath.setPlaceholderText("Leave this empty to use your default browser") ui.toolButton_Browse.clicked.connect(self.browseClicked) # load settings settings = QSettings() ui.lineEdit_BrowserPath.setText(settings.value("/Qgis2threejs/browser", "", type=unicode)) enabled_plugins = QSettings().value("/Qgis2threejs/plugins", "", type=unicode).split(",") # initialize plugin table widget plugin_dir = QDir(os.path.join(os.path.dirname(QFile.decodeName(__file__)), "plugins")) plugins = plugin_dir.entryList(QDir.Dirs | QDir.NoSymLinks | QDir.NoDotAndDotDot) tableWidget = ui.tableWidget_Plugins tableWidget.setRowCount(len(plugins)) tableWidget.setColumnCount(1) tableWidget.setHorizontalHeaderLabels(["Name"]) tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows) headerView = tableWidget.horizontalHeader() headerView.setResizeMode(0, QHeaderView.Stretch) self.plugin_metadata = [] for i, name in enumerate(plugins): parser = ConfigParser.SafeConfigParser() with codecs.open(os.path.join(plugin_dir.absoluteFilePath(name), "metadata.txt"), "r", "UTF-8") as f: parser.readfp(f) metadata = dict(parser.items("general")) self.plugin_metadata.append(metadata) item = QTableWidgetItem(metadata.get("name", name)) item.setCheckState(Qt.Checked if name in enabled_plugins else Qt.Unchecked) tableWidget.setItem(i, 0, item) tableWidget.selectionModel().currentRowChanged.connect(self.pluginSelectionChanged)
def set_data(plugins, table): table.setHorizontalHeaderLabels(["Name", "Version", "Description"]) table.horizontalHeader().setStretchLastSection(True) table.setSelectionBehavior(QAbstractItemView.SelectRows) for i in xrange(table.rowCount()): table.removeRow(0) r = 0 for plug in plugins: table.insertRow(r) # Column 2 item = QTableWidgetItem(plug[1]) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) table.setItem(r, 2, item) # Column 1 item = QTableWidgetItem(plug[2]) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) table.setItem(r, 1, item) # Column 0 item = QTableWidgetItem(plug[0]) table.setItem(r, 0, item) item.setCheckState(Qt.Unchecked) r += 1
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)
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()
def populateFieldTable(self): if self.collectedDataDict: importingFields = self.collectedDataDict[0].keys() self.fieldTable.clear() self.fieldTable.setRowCount(len(importingFields)) predefinedFields = ['EOMETRY','UUID'] 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) for predef in predefinedFields: if predef in field.upper(): #prevent predefined fields user editing if predef == 'UUID': ODKfieldItem.setText(field) QGISfieldItem.setText('ODKUUID') elif predef == '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)
def load(self, error=True): s = QSettings( "norBIT", "norGIS-ALKIS-Erweiterung" ) s.setValue( "service", self.leSERVICE.text() ) s.setValue( "host", self.leHOST.text() ) s.setValue( "port", self.lePORT.text() ) s.setValue( "dbname", self.leDBNAME.text() ) s.setValue( "uid", self.leUID.text() ) s.setValue( "pwd", self.lePWD.text() ) if hasattr(qgis.gui,'QgsAuthConfigSelect'): s.setValue( "authcfg", self.authCfgSelect.configId() ) self.twModellarten.clearContents() self.cbxSignaturkatalog.clear() modelle = s.value( "modellarten", ['DLKM','DKKM1000'] ) if modelle is None: modelle = ['DLKM','DKKM1000'] (db,conninfo) = self.plugin.opendb() if not db: if error: QMessageBox.critical( None, "ALKIS", u"Datenbankverbindung schlug fehl." ) return qry = QSqlQuery(db) if qry.exec_( """ SELECT modell,count(*) FROM ( SELECT unnest(modell) AS modell FROM po_points UNION ALL SELECT unnest(modell) AS modell FROM po_lines UNION ALL SELECT unnest(modell) AS modell FROM po_polygons UNION ALL SELECT unnest(modell) AS modell from po_lines UNION ALL SELECT unnest(modell) AS modell from po_labels ) AS foo GROUP BY modell ORDER BY count(*) DESC """ ): res = {} while qry.next(): res[ qry.value(0) ] = qry.value(1) self.twModellarten.setRowCount( len(res) ) i = 0 for k,n in sorted(res.iteritems(), key=operator.itemgetter(1), reverse=True): item = QTableWidgetItem( k ) item.setCheckState( Qt.Checked if (item.text() in modelle) else Qt.Unchecked ) self.twModellarten.setItem( i, 0, item ) item = QTableWidgetItem( str(n) ) self.twModellarten.setItem( i, 1, item ) i += 1 self.twModellarten.resizeColumnsToContents() self.twModellarten.setEnabled( True ) else: modelle = [] self.twModellarten.clearContents() self.twModellarten.setDisabled( True ) if qry.exec_( "SELECT id,name FROM alkis_signaturkataloge" ): while qry.next(): self.cbxSignaturkatalog.addItem( qry.value(1), int(qry.value(0)) ) self.cbxSignaturkatalog.setEnabled( True ) else: self.cbxSignaturkatalog.addItem( u"Farbe", -1 ) self.cbxSignaturkatalog.setCurrentIndex( max( [ 0, self.cbxSignaturkatalog.findData( s.value( "signaturkatalog", -1 ) ) ] ) )
def saveParameters(self): self.updateDistricts() layers = self.iface.legendInterface().layers() selectedLayerIndex = self.dlgparameters.cmbActiveLayer.currentIndex() selectedLayer = layers[selectedLayerIndex] self.activeLayer = selectedLayer self.districts = self.dlgparameters.inpDistricts.value() self.activedistrict = 1 self.dockwidget.lblActiveDistrict.setText("Active District: " + str(self.activedistrict)) self.dockwidget.sliderDistricts.setMinimum(1) self.dockwidget.sliderDistricts.setMaximum(self.districts) self.dockwidget.sliderDistricts.setValue(1) self.popfield = self.dlgparameters.cmbPopField.currentText() self.distfield = self.dlgparameters.cmbDistField.currentText() # self.dispfield1 = self.dlgparameters.cmbDispField1.currentText() # self.dispfield2 = self.dlgparameters.cmbDispField1.currentText() QgsMessageLog.logMessage("Popfield:" + str(self.popfield)) self.totalpop = 0 self.targetpop = 0 for feature in self.activeLayer.getFeatures(): self.totalpop = self.totalpop + feature[self.popfield] self.targetpop = int(self.totalpop / self.districts) self.targetpoppct = self.dlgparameters.inpTolerance.value() targetpoprem = int((self.targetpop / 100) * self.targetpoppct) self.targetpoplower = int(self.targetpop - targetpoprem) self.targetpophigher = int(self.targetpop + targetpoprem + 1) QgsMessageLog.logMessage("TargetPop:" + str(self.targetpop) + "(" + str(self.targetpoplower) + ", " + str(self.targetpophigher) + ")") QgsMessageLog.logMessage("Districts:" + str(self.districts)) self.dockwidget.lblMainInfo.setText("Active Layer: " + self.activeLayer.name() + "\nActive District Field: " + self.distfield + "\nTarget Population: " + str(self.targetpop) + " (" + str(self.targetpoplower) + ", " + str(self.targetpophigher) + ")") self.attrdockwidget.tblPop.setRowCount(self.districts + 1) numDataFields = 0 for d in dataFieldList: numDataFields = numDataFields + 1 self.attrdockwidget.tblPop.setHorizontalHeaderItem( 2 + numDataFields, QTableWidgetItem(d.name)) self.attrdockwidget.tblPop.setColumnCount(4 + numDataFields) for r in range(0, self.districts + 1): chkBoxItem = QTableWidgetItem() chkBoxItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) chkBoxItem.setCheckState(Qt.Unchecked) self.attrdockwidget.tblPop.setItem(r, 1, chkBoxItem) self.attrdockwidget.tblPop.setHorizontalHeaderLabels( ['#', 'Lock', 'Population', 'To Target']) numDataFields = 0 for d in dataFieldList: numDataFields = numDataFields + 1 if d.type == 1: self.attrdockwidget.tblPop.setHorizontalHeaderItem( 3 + numDataFields, QTableWidgetItem(d.name)) else: self.attrdockwidget.tblPop.setHorizontalHeaderItem( 3 + numDataFields, QTableWidgetItem(d.name + '%')) if len(districtName) == 0: self.initializeElectorates() try: self.saveParametersToFile() QgsMessageLog.logMessage("Parameters file saved!") except: QgsMessageLog.logMessage("Parameters file could not be saved") if self.dlgparameters.chkStyleMap.isChecked(): categories = [] for cat in range(0, self.districts + 1): symbol = QgsSymbolV2.defaultSymbol( self.activeLayer.geometryType()) layer_style = {} layer_style['color'] = '%d, %d, %d' % (randrange( 0, 256), randrange(0, 256), randrange(0, 256)) layer_style['outline'] = '#000000' symbol_layer = QgsSimpleFillSymbolLayerV2.create(layer_style) # replace default symbol layer with the configured one if symbol_layer is not None: symbol.changeSymbolLayer(0, symbol_layer) # create renderer object category = QgsRendererCategoryV2(cat, symbol, str(cat)) # entry for the list of category items categories.append(category) renderer = QgsCategorizedSymbolRendererV2(self.distfield, categories) # assign the created renderer to the layer if renderer is not None: self.activeLayer.setRendererV2(renderer) self.activeLayer.triggerRepaint() self.updateFieldValues() self.updateTable() self.updateLockedFields() self.updateDistricts()
def _item(self, content, is_checkable): item = QTableWidgetItem(content) if is_checkable: item.setCheckState(Qt.Unchecked) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable) return item
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()
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()
def setSnapshotTable(self, data, table, eventid): if data: length = len(data.values()[0]) else: print ('data is empty, exit.') return for i in range(1, len(data.values())): if length != len(data.values()[i]): QMessageBox.warning(self, "Warning", "Data length are not consistent.") return if isinstance(data, odict) and isinstance(table, QTableWidget): table.setSortingEnabled(False) table.clear() nrows = len(data.values()[0]) # ('pv name label', 'dbr_type label', 'string value', 'int value', 'double value', 'status label', 'severity label', # 'ioc time stamp label', 'ioc time stamp nano label', 'is_array', 'array_value'), # => (pv_name, status, severity, ioc_timestamp, saved value) # ncols = len(data) - 6 # ncols = ncols + 3 # 2 columns for live data and (live data - saved data), selected restore pv ncols = len(data) - 3 table.setRowCount(nrows) table.setColumnCount(ncols) pvnames = data['PV Name'] status = data['Status'] severity = data['Severity'] ts = data['Time stamp'] ts_nano = data['Time stamp (nano)'] dbrtype = data['DBR'] s_value = data['S_value'] i_value = data['I_value'] d_value = data['D_value'] isConnected = data['isConnected'] is_array = data['isArray'] array_value = data['arrayValue'] keys = ['Name', 'Status', 'Severity', 'Time Stamp', 'Connection', 'Saved Value', 'Live Value', 'Delta', 'Not Restore'] table.setHorizontalHeaderLabels(keys) for i in range(nrows): item = table.item(i, 8) if item: item.setCheckState(False) else: item = QTableWidgetItem() item.setFlags(Qt.ItemIsEnabled|Qt.ItemIsUserCheckable) table.setItem(i, 8, item) item.setCheckState(False) if pvnames[i]: self.__setTableItem(table, i, 0, pvnames[i]) if status[i]: self.__setTableItem(table, i, 1, str(status[i])) if severity[i]: self.__setTableItem(table, i, 2, str(severity[i])) if ts[i]: dt = str(datetime.datetime.fromtimestamp(ts[i]+ts_nano[i]*1.0e-9)) self.__setTableItem(table, i, 3, dt) if is_array[i]: self.__setTableItem(table, i, 5, self.__arrayTextFormat(array_value[i])) self.arrayData[pvnames[i]+'_'+str(eventid)] = array_value[i] else: if dbrtype[i] in self.epicsDouble: self.__setTableItem(table, i, 5, str(d_value[i])) elif dbrtype[i] in self.epicsLong: self.__setTableItem(table, i, 5, str(i_value[i])) elif dbrtype[i] in self.epicsString: self.__setTableItem(table, i, 5, str(s_value[i])) elif dbrtype[i] in self.epicsNoAccess: # channel are not connected. pass else: print('invalid dbr type (code = %s)'%(dbrtype[i])) if isConnected[i]: self.__setTableItem(table, i, 4, str(bool(isConnected[i]))) item.setFlags(item.flags() | Qt.ItemIsUserCheckable) else: self.__setTableItem(table, i, 4, 'False') item.setCheckState(True) item.setSelected(True) # disable user checkable function item.setFlags(item.flags() ^ Qt.ItemIsUserCheckable) for item_idx in range(9): itemtmp = table.item(i, item_idx) if not itemtmp: itemtmp = QTableWidgetItem() table.setItem(i, item_idx, itemtmp) itemtmp.setBackground(self.brushbadpv) table.setSortingEnabled(True) else: raise "Either given data is not an instance of OrderedDict or table is not an instance of QtGui.QTableWidget"
def _item(self, content, is_checkable): item = QTableWidgetItem(str(content)) if is_checkable: item.setCheckState(Qt.Unchecked) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable) return item