def init_ui(self): model = QStandardItemModel() model.insertColumns(0, 4) model.setHeaderData(0, 1, 'ID', 0) model.setHeaderData(1, 1, 'Sigle', 0) model.setHeaderData(2, 1, 'Parameter', 0) model.setHeaderData(3, 1, 'Value', 0) sql = "SELECT id, sigle, text, value FROM {0}.tracer_physic WHERE type = '{1}' ORDER BY id".format( self.mdb.SCHEMA, self.cur_wq_mod) rows = self.mdb.run_query(sql, fetch=True) model.insertRows(0, len(rows)) for r, row in enumerate(rows): for c, val in enumerate(row): itm = QStandardItem() itm.setData(val, 0) if c == 3: itm.setData(data_to_float(val), 0) itm.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled | Qt.ItemIsEditable) itm.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) else: itm.setData(val, 0) itm.setFlags(Qt.ItemIsEnabled) model.setItem(r, c, itm) self.ui.tab_param.setModel(model) self.ui.tab_param.hide() self.ui.tab_param.resizeColumnsToContents() self.ui.tab_param.resizeRowsToContents() self.ui.tab_param.setColumnHidden(0, True) self.ui.ui.tab_param.show()
def setValue(self, table): cols = len(table[0]) rows = len(table) model = QStandardItemModel(rows, cols) for i in range(rows): for j in range(cols): item = QStandardItem(str(table[i][j])) model.setItem(i, j, item) self.tblView.setModel(model)
def setValue(self, table): cols = len(table[0]) rows = len(table) model = QStandardItemModel(rows, cols) for i in range(rows): for j in range(cols): item = QStandardItem(str(table[i][j])) model.setItem(i, j, item) self.tblView.setModel(model)
def setValue(self, headers, table): model = self.tblView.model() model.setHorizontalHeaderLabels(headers) cols = len(headers) rows = len(table) // cols model = QStandardItemModel(rows, cols) for row in range(rows): for col in range(cols): item = QStandardItem(str(table[row * cols + col])) model.setItem(row, col, item) self.tblView.setModel(model)
def setValue(self, headers, table): model = self.tblView.model() model.setHorizontalHeaderLabels(headers) cols = len(headers) rows = len(table) // cols model = QStandardItemModel(rows, cols) for row in range(rows): for col in range(cols): item = QStandardItem(str(table[row * cols + col])) model.setItem(row, col, item) self.tblView.setModel(model)
def populateTable(self, table): cols = len(self.param.headers()) rows = len(table) // cols model = QStandardItemModel(rows, cols) # Set headers model.setHorizontalHeaderLabels(self.param.headers()) # Populate table for row in range(rows): for col in range(cols): item = QStandardItem(str(table[row * cols + col])) model.setItem(row, col, item) self.tblView.setModel(model)
def populateTable(self, table): cols = len(self.param.cols) rows = len(table) model = QStandardItemModel(rows, cols) # Set headers model.setHorizontalHeaderLabels(self.param.cols) # Populate table for i in range(rows): for j in range(cols): item = QStandardItem(table[i][j]) model.setItem(i, j, item) self.tblView.setModel(model)
def populateTable(self, table): cols = len(self.param.headers()) rows = len(table) // cols model = QStandardItemModel(rows, cols) # Set headers model.setHorizontalHeaderLabels(self.param.headers()) # Populate table for row in range(rows): for col in range(cols): item = QStandardItem(str(table[row * cols + col])) model.setItem(row, col, item) self.tblView.setModel(model)
def populateTable(self, table): cols = len(self.param.cols) rows = len(table) model = QStandardItemModel(rows, cols) # Set headers model.setHorizontalHeaderLabels(self.param.cols) # Populate table for i in range(rows): for j in range(cols): item = QStandardItem(table[i][j]) model.setItem(i, j, item) self.tblView.setModel(model)
def populate_columns_list(self): """ Populate the columns view. :return: :rtype: """ options = {} options['type'] = 'combobox' delegate = GenericDelegate(self.separators, options, self.column_code_view) # Set delegate to add widget self.column_code_view.setItemDelegate(delegate) self.column_code_view.setItemDelegateForColumn(1, delegate) model = QStandardItemModel(2, 2) i = 0 for row, col in enumerate(self._columns): column_item = QStandardItem(self._entity.columns[col].header()) column_item.setCheckable(True) model.setItem(i, 0, column_item) column_item.setData(col) self.column_code_view.setModel(model) i = i + 1 for col in self._entity.columns.values(): if col.name == 'id': continue if col.name not in self._columns: # Correct row by reducing by one due to removal of id column_item = QStandardItem(col.header()) column_item.setCheckable(True) model.setItem(i, 0, column_item) column_item.setData(col.name) self.column_code_view.setModel(model) i = i + 1
class PosiviewProperties(QgsOptionsDialogBase, Ui_PosiviewPropertiesBase): ''' GUI class classdocs for the Configuration dialog ''' applyChanges = pyqtSignal(dict) def __init__(self, project, parent=None): ''' Setup dialog widgets with the project properties ''' super(PosiviewProperties, self).__init__("PosiViewProperties", parent) self.setupUi(self) self.groupBox_6.hide() self.initOptionsBase(False) self.restoreOptionsBaseUi() self.comboBoxParser.addItems(PARSERS) self.comboBoxProviderType.addItems(DEVICE_TYPES) self.project = project self.projectProperties = project.properties() self.mToolButtonLoad.setDefaultAction(self.actionLoadConfiguration) self.mToolButtonSave.setDefaultAction(self.actionSaveConfiguration) self.mobileModel = QStringListModel() self.mobileListModel = QStringListModel() self.mMobileListView.setModel(self.mobileListModel) self.mobileProviderModel = QStandardItemModel() self.mobileProviderModel.setHorizontalHeaderLabels( ('Provider', 'Filter')) self.mMobileProviderTableView.setModel(self.mobileProviderModel) self.providerListModel = QStringListModel() self.mDataProviderListView.setModel(self.providerListModel) self.comboBoxProviders.setModel(self.providerListModel) self.setupModelData(self.projectProperties) self.setupGeneralData(self.projectProperties) def setupModelData(self, properties): self.mobileListModel.setStringList(sorted( properties['Mobiles'].keys())) self.providerListModel.setStringList( sorted(properties['Provider'].keys())) def setupGeneralData(self, properties): self.lineEditCruise.setText(properties['Mission']['cruise']) self.lineEditDive.setText(properties['Mission']['dive']) self.lineEditStation.setText(properties['Mission']['station']) self.lineEditRecorderPath.setText(properties['RecorderPath']) self.checkBoxAutoRecording.setChecked(properties['AutoRecord']) self.spinBoxNotifyDuration.setValue(properties['NotifyDuration']) self.checkBoxUtcClock.setChecked(properties['ShowUtcClock']) self.checkBoxWithSuffix.setChecked(properties['DefaultFormat'] & 4) self.comboBoxDefaultPositionFormat.setCurrentIndex( (properties['DefaultFormat']) & 3) def updateGeneralData(self): self.projectProperties['Mission']['cruise'] = self.lineEditCruise.text( ) self.projectProperties['Mission']['dive'] = self.lineEditDive.text() self.projectProperties['Mission'][ 'station'] = self.lineEditStation.text() self.projectProperties[ 'RecorderPath'] = self.lineEditRecorderPath.text() self.projectProperties[ 'AutoRecord'] = self.checkBoxAutoRecording.isChecked() self.projectProperties[ 'NotifyDuration'] = self.spinBoxNotifyDuration.value() self.projectProperties[ 'ShowUtcClock'] = self.checkBoxUtcClock.isChecked() self.projectProperties[ 'DefaultFormat'] = self.comboBoxDefaultPositionFormat.currentIndex( ) if self.checkBoxWithSuffix.isChecked(): self.projectProperties['DefaultFormat'] |= 4 def getColor(self, value): try: return QColor.fromRgba(int(value)) except ValueError: return QColor(value) @pyqtSlot(QAbstractButton, name='on_buttonBox_clicked') def onButtonBoxClicked(self, button): role = self.buttonBox.buttonRole(button) if role == QDialogButtonBox.ApplyRole or role == QDialogButtonBox.AcceptRole: self.updateGeneralData() self.applyChanges.emit(self.projectProperties) @pyqtSlot(name='on_actionSaveConfiguration_triggered') def onActionSaveConfigurationTriggered(self): ''' Save the current configuration ''' fn, __ = QFileDialog.getSaveFileName(None, 'Save PosiView configuration', '', 'Configuration (*.ini *.conf)') if fn: if not os.path.splitext(fn)[1]: fn += u'.conf' self.project.store(fn) @pyqtSlot(name='on_actionLoadConfiguration_triggered') def onActionLoadConfigurationTriggered(self): ''' Load configuration from file ''' fn, __ = QFileDialog.getOpenFileName(None, 'Save PosiView configuration', '', 'Configuration (*.ini *.conf)') self.projectProperties = self.project.read(fn) self.setupModelData(self.projectProperties) self.setupGeneralData(self.projectProperties) @pyqtSlot(QModelIndex, name='on_mMobileListView_clicked') def editMobile(self, index): ''' Populate the widgets with the selected mobiles properties ''' if index.isValid(): self.populateMobileWidgets(index) @pyqtSlot(str, name='on_comboBoxMobileType_currentIndexChanged') def mobileTypeChanged(self, mType): if mType == 'SHAPE': self.lineEditMobileShape.setEnabled(True) else: self.lineEditMobileShape.setEnabled(False) @pyqtSlot(QModelIndex, name='on_mMobileListView_activated') def activated(self, index): pass @pyqtSlot(name='on_toolButtonAddMobile_clicked') def addMobile(self): self.mobileListModel.insertRow(self.mobileListModel.rowCount()) index = self.mobileListModel.index(self.mobileListModel.rowCount() - 1) self.lineEditMobileName.setText('NewMobile') self.mobileListModel.setData(index, 'NewMobile', Qt.DisplayRole) self.mMobileListView.setCurrentIndex(index) self.applyMobile() @pyqtSlot(name='on_pushButtonApplyMobile_clicked') def applyMobile(self): index = self.mMobileListView.currentIndex() if index.isValid() and not self.lineEditMobileName.text() == '': mobile = dict() mobile['Name'] = self.lineEditMobileName.text() mobile['type'] = self.comboBoxMobileType.currentText() try: t = eval(self.lineEditMobileShape.text()) if t.__class__ is tuple or t.__class__ is dict: mobile['shape'] = t except SyntaxError: mobile['shape'] = ((0.0, -0.5), (0.3, 0.5), (0.0, 0.2), (-0.5, 0.5)) mobile['length'] = self.doubleSpinBoxMobileLength.value() mobile['width'] = self.doubleSpinBoxMobileWidth.value() mobile['defaultIcon'] = self.checkBoxDefaultIcon.isChecked() mobile['defaultIconFilled'] = self.checkBoxDefIconFilled.isChecked( ) mobile['offsetX'] = self.doubleSpinBoxXOffset.value() mobile['offsetY'] = self.doubleSpinBoxYOffset.value() mobile['zValue'] = self.spinBoxZValue.value() mobile['color'] = self.mColorButtonMobileColor.color().rgba() mobile['fillColor'] = self.mColorButtonMobileFillColor.color( ).rgba() mobile['timeout'] = self.spinBoxMobileTimeout.value() * 1000 mobile['nofixNotify'] = self.spinBoxMobileNotification.value() mobile['fadeOut'] = self.checkBoxFadeOut.isChecked() mobile['trackLength'] = self.spinBoxTrackLength.value() mobile['trackColor'] = self.mColorButtonMobileTrackColor.color( ).rgba() mobile['showLabel'] = self.checkBoxShowLabel.isChecked() provs = dict() for r in range(self.mobileProviderModel.rowCount()): try: fil = int( self.mobileProviderModel.item(r, 1).data(Qt.DisplayRole)) except Exception: fil = self.mobileProviderModel.item(r, 1).data(Qt.DisplayRole) if not fil: fil = None provs[self.mobileProviderModel.item(r, 0).data( Qt.DisplayRole)] = fil mobile['provider'] = provs currName = self.mobileListModel.data(index, Qt.DisplayRole) if not currName == mobile['Name']: del self.projectProperties['Mobiles'][currName] self.mobileListModel.setData(index, mobile['Name'], Qt.DisplayRole) self.projectProperties['Mobiles'][mobile['Name']] = mobile def populateMobileWidgets(self, index): mobile = self.projectProperties['Mobiles'][self.mobileListModel.data( index, Qt.DisplayRole)] self.lineEditMobileName.setText(mobile.get('Name')) self.comboBoxMobileType.setCurrentIndex( self.comboBoxMobileType.findText( mobile.setdefault('type', 'BOX').upper())) if mobile['type'] == 'SHAPE': self.lineEditMobileShape.setText(str(mobile['shape'])) self.lineEditMobileShape.setEnabled(True) self.doubleSpinBoxXOffset.setEnabled(True) self.doubleSpinBoxYOffset.setEnabled(True) else: self.lineEditMobileShape.setEnabled(False) self.doubleSpinBoxXOffset.setEnabled(False) self.doubleSpinBoxYOffset.setEnabled(False) self.lineEditMobileShape.clear() self.doubleSpinBoxMobileLength.setValue(mobile.get('length', 20.0)) self.doubleSpinBoxMobileWidth.setValue(mobile.get('width', 5.0)) self.checkBoxDefaultIcon.setChecked(mobile.get('defaultIcon', True)) self.checkBoxDefIconFilled.setChecked( mobile.get('defaultIconFilled', False)) self.doubleSpinBoxXOffset.setValue(mobile.get('offsetX', 0.0)) self.doubleSpinBoxYOffset.setValue(mobile.get('offsetY', 0.0)) self.spinBoxZValue.setValue(mobile.get('zValue', 100)) self.mColorButtonMobileColor.setColor( self.getColor(mobile.get('color', 'black'))) self.mColorButtonMobileFillColor.setColor( self.getColor(mobile.get('fillColor', 'green'))) self.spinBoxMobileTimeout.setValue(mobile.get('timeout', 3000) / 1000) self.spinBoxMobileNotification.setValue(mobile.get('nofixNotify', 0)) self.checkBoxFadeOut.setChecked(mobile.get('fadeOut', False)) self.spinBoxTrackLength.setValue(mobile.get('trackLength', 100)) self.mColorButtonMobileTrackColor.setColor( self.getColor(mobile.get('trackColor', 'green'))) self.checkBoxShowLabel.setChecked(mobile.get('showLabel', False)) r = 0 self.mobileProviderModel.removeRows( 0, self.mobileProviderModel.rowCount()) if 'provider' in mobile: for k, v in list(mobile['provider'].items()): prov = QStandardItem(k) val = QStandardItem(str(v)) self.mobileProviderModel.setItem(r, 0, prov) self.mobileProviderModel.setItem(r, 1, val) r += 1 @pyqtSlot(name='on_toolButtonRemoveMobile_clicked') def removeMobile(self): idx = self.mMobileListView.currentIndex() if idx.isValid(): self.projectProperties['Mobiles'].pop( self.mobileListModel.data(idx, Qt.DisplayRole)) self.mobileListModel.removeRows(idx.row(), 1) idx = self.mMobileListView.currentIndex() if idx.isValid(): self.populateMobileWidgets(idx) @pyqtSlot(name='on_toolButtonRefreshMobileProvider_clicked') def refreshMobileProvider(self): prov = self.comboBoxProviders.currentText() if prov == '': return fil = None if self.lineEditProviderFilter.text() != '': fil = self.lineEditProviderFilter.text() items = self.mobileProviderModel.findItems(prov, Qt.MatchExactly, 0) if items: for item in items: self.mobileProviderModel.setItem(item.row(), 1, QStandardItem(fil)) else: self.mobileProviderModel.appendRow( [QStandardItem(prov), QStandardItem(fil)]) @pyqtSlot(name='on_toolButtonRemoveMobileProvider_clicked') def removeMobileProvider(self): idx = self.mMobileProviderTableView.currentIndex() if idx.isValid(): self.mobileProviderModel.removeRow(idx.row()) @pyqtSlot(name='on_pushButtonApplyDataProvider_clicked') def applyDataProvider(self): index = self.mDataProviderListView.currentIndex() if index.isValid() and not self.lineEditProviderName.text() == '': provider = dict() provider['Name'] = self.lineEditProviderName.text() provider['DataDeviceType'] = self.comboBoxProviderType.currentText( ) if provider['DataDeviceType'] in NETWORK_TYPES: provider['Host'] = self.lineEditProviderHostName.text() provider['Port'] = self.spinBoxProviderPort.value() provider['Parser'] = self.comboBoxParser.currentText() currName = self.providerListModel.data(index, Qt.DisplayRole) if not currName == provider['Name']: del self.projectProperties['Provider'][currName] self.providerListModel.setData(index, provider['Name'], Qt.DisplayRole) self.projectProperties['Provider'][provider['Name']] = provider @pyqtSlot(QModelIndex, name='on_mDataProviderListView_clicked') def editDataProvider(self, index): ''' ''' if index.isValid(): self.populateDataProviderWidgets(index) def populateDataProviderWidgets(self, index): provider = self.projectProperties['Provider'][ self.providerListModel.data(index, Qt.DisplayRole)] self.lineEditProviderName.setText(provider.get('Name')) self.comboBoxProviderType.setCurrentIndex( self.comboBoxProviderType.findText( provider.setdefault('DataDeviceType', 'UDP').upper())) if provider['DataDeviceType'] in NETWORK_TYPES: self.stackedWidgetDataDevice.setCurrentIndex(0) self.lineEditProviderHostName.setText( provider.setdefault('Host', '0.0.0.0')) self.spinBoxProviderPort.setValue( int(provider.setdefault('Port', 2000))) self.comboBoxParser.setCurrentIndex( self.comboBoxParser.findText( provider.setdefault('Parser', 'NONE').upper())) @pyqtSlot(name='on_toolButtonAddDataProvider_clicked') def addDataProvider(self): self.providerListModel.insertRow(self.providerListModel.rowCount()) index = self.providerListModel.index( self.providerListModel.rowCount() - 1) self.lineEditProviderName.setText('NewDataProvider') self.providerListModel.setData(index, 'NewDataProvider', Qt.DisplayRole) self.mDataProviderListView.setCurrentIndex(index) self.applyDataProvider() @pyqtSlot(name='on_toolButtonRemoveDataProvider_clicked') def removeDataProvider(self): idx = self.mDataProviderListView.currentIndex() if idx.isValid(): self.projectProperties['Provider'].pop( self.providerListModel.data(idx, Qt.DisplayRole)) self.providerListModel.removeRows(idx.row(), 1) idx = self.mDataProviderListView.currentIndex() if idx.isValid(): self.populateDataProviderWidgets(idx) @pyqtSlot(name='on_toolButtonSelectLogPath_clicked') def selectRecorderPath(self): path = QFileDialog.getExistingDirectory( self, self.tr('Select Recorder Path'), self.lineEditRecorderPath.text(), QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks) if path != '': self.lineEditRecorderPath.setText(path) @pyqtSlot(QPoint, name='on_lineEditMobileShape_customContextMenuRequested') def mobileShapeContextMenu(self, pos): menu = QMenu(self.lineEditMobileShape) vesselAction = menu.addAction(self.tr('Vessel')) rovAction = menu.addAction(self.tr('ROV')) auvAction = menu.addAction(self.tr('AUV')) arrowAction = menu.addAction(self.tr('Arrow')) selectedAction = menu.exec_(self.lineEditMobileShape.mapToGlobal(pos)) if selectedAction == vesselAction: self.lineEditMobileShape.setText( u'((0, -0.5), (0.5, -0.3), (0.5, 0.5), (-0.5, 0.5), (-0.5, -0.3))' ) elif selectedAction == rovAction: self.lineEditMobileShape.setText( u'((0.3, -0.5), (0.5, -0.3), (0.5, 0.5), (-0.5, 0.5), (-0.5, -0.3), (-0.3, -0.5))' ) elif selectedAction == auvAction: self.lineEditMobileShape.setText( u'((0, -0.5), (0.4, -0.3), (0.5, -0.3), (0.5, -0.2), (0.4, -0.2), (0.4, 0.3), (0.5, 0.3), (0.5, 0.4), (0.4, 0.4), (0.0, 0.5), \ (-0.4, 0.4), (-0.5, 0.4), (-0.5, 0.3), (-0.4, 0.3), (-0.4, -0.2), (-0.5, -0.2), (-0.5, -0.3), (-0.4, -0.3))' ) elif selectedAction == arrowAction: self.lineEditMobileShape.setText( u'((0, -0.5), (0.5, 0.5), (0, 0), (-0.5, 0.5))') @pyqtSlot(name='on_buttonBox_helpRequested') def showHelp(self): """Display application help to the user.""" help_file = os.path.join( os.path.split(os.path.dirname(__file__))[0], 'help', 'index.html') QDesktopServices.openUrl(QUrl.fromLocalFile(help_file))
class manageAccountsDlg(WIDGET, BASE): ''' User- and Role-management dialog class ''' def __init__(self, plugin): QDialog.__init__(self, plugin.iface.mainWindow()) self.setupUi(self) QgsGui.enableAutoGeometryRestore(self) self.tbUserRole.setTabIcon(0, GuiUtils.get_icon('user.png')) self.tbUserRole.setTabIcon(1, GuiUtils.get_icon('roles.png')) self.tbUserRole.setTabIcon(2, GuiUtils.get_icon('user_mapping.png')) # Initialize the dialog self.initGui() # Load users self.loadUsers() # Load Roles self.loadRoles() # Load user mappings self.loadUserMappings() # Reference to the currently selected STDM role for which user mappings need to be defined self.currentRole = None def initGui(self): ''' Set control properties ''' # Set properties for 'Users' button box btnUserNew = self.btnManageUsers.button(QDialogButtonBox.Ok) btnUserNew.setText(QApplication.translate("manageAccountsDlg", "New") + "...") btnUserNew.clicked.connect(self.onNewUser) btnUserEdit = self.btnManageUsers.button(QDialogButtonBox.Save) btnUserEdit.setText(QApplication.translate("manageAccountsDlg", "Edit")) btnUserEdit.clicked.connect(self.onEditUser) btnUserDelete = self.btnManageUsers.button(QDialogButtonBox.Cancel) btnUserDelete.setText(QApplication.translate("manageAccountsDlg", "Delete")) btnUserDelete.clicked.connect(self.onDeleteUser) # Set properties for 'Roles' button box btnRoleNew = self.btnManageRoles.button(QDialogButtonBox.Ok) btnRoleNew.setText(QApplication.translate("manageAccountsDlg", "New") + "...") btnRoleNew.clicked.connect(self.onNewRole) btnRoleDelete = self.btnManageRoles.button(QDialogButtonBox.Cancel) btnRoleDelete.setText(QApplication.translate("manageAccountsDlg", "Delete")) btnRoleDelete.clicked.connect(self.onDeleteRole) btnRoleSync = self.btnManageRoles.button(QDialogButtonBox.Apply) btnRoleSync.setText(QApplication.translate("manageAccountsDlg", "Sync")) btnRoleSync.setToolTip( QApplication.translate("manageAccountsDlg", "Synchronize STDM roles with database roles")) btnRoleSync.clicked.connect(self.onSyncRoles) # Data view signals self.lstRoles.clicked.connect(self.onRoleSelected) self.lstRoles.activated.connect(self.onRoleSelected) self.lstMappingRoles.clicked.connect(self.onRoleMappingSelected) self.lstMappingRoles.activated.connect(self.onRoleMappingSelected) self.lstMappingUsers.clicked.connect(self.onUserMappingSelected) self.lstMappingUsers.activated.connect(self.onUserMappingSelected) # Disable any action by the user in the user roles mapping list view self.lstMappingUsers.setEnabled(False) def onNewUser(self): ''' Slot activated when the user requests to create a new user ''' frmNewUser = newUserDlg(self) result = frmNewUser.exec_() # Add new user to dependent models if result == QDialog.Accepted: user = frmNewUser.user # Add new user to Users view numUsers = self.usersModel.rowCount() self.usersModel.insertRows(numUsers, 1) index = self.usersModel.index(numUsers) self.usersModel.setData(index, user.UserName) # Add the user to the user mappings list userItem = self._createNewUserMapping(user.UserName) numUsers = self.UserMappingsModel.rowCount() self.UserMappingsModel.setItem(numUsers, userItem) # Sort users self.sortUsers() def loadUsers(self): ''' Loads the names of existing users ''' self.membership = Membership() users = self.membership.getAllUsers() self.usersModel = UsersRolesModel(users) self.sortUsers() self.lstUsers.setModel(self.usersModel) def loadRoles(self): ''' Loads the roles of the database cluster ''' self.roleProvider = RoleProvider() roles = self.roleProvider.GetAllRoles() roleNames = [] # Remove the postgresql role if it exists for role in roles: if role.name != 'postgres': roleNames.append(role.name) self.rolesModel = UsersRolesModel(roleNames) self.sortRoles() self.lstRoles.setModel(self.rolesModel) # Load mapping roles view as well self.lstMappingRoles.setModel(self.rolesModel) def onEditUser(self): ''' Slot activated for editing a selected user ''' selItems = self.lstUsers.selectionModel().selectedRows() if len(selItems) == 0: msg = QApplication.translate("manageAccountsDlg", "Please select a user to edit.") QMessageBox.warning(self, QApplication.translate("manageAccountsDlg", "Select User"), msg) return # Get user from the first item in the selection username = selItems[0].data() user = self.membership.getUser(username) if user != None: frmUserUpdate = newUserDlg(self, user) frmUserUpdate.exec_() def onDeleteUser(self): ''' Slot activated for deleting a selected user ''' selItems = self.lstUsers.selectionModel().selectedRows() if len(selItems) == 0: msg = QApplication.translate("manageAccountsDlg", "Please select a user to delete.") QMessageBox.warning(self, QApplication.translate("manageAccountsDlg", "Select User"), msg) return # Get user from the first item in the selection userIndex = selItems[0] username = userIndex.data() msg = QApplication.translate("manageAccountsDlg", "Are you sure you want to delete '%s'?\nOnce deleted, this user account cannot be recovered." % ( username,)) result = QMessageBox.warning(self, QApplication.translate("manageAccountsDlg", "Delete User"), msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if result == QMessageBox.Yes: # Delete the user self.membership.deleteUser(username) # Remove user from the list self.usersModel.removeRows(userIndex.row(), 1) # Remove corresponding item from the user mapping list view self.UserMappingsModel.removeRow(userIndex.row()) # Sort users self.sortUsers() def onSyncRoles(self): ''' Slot for synchronizing STDM roles with database cluster roles. This is very important especially on first time login by the superuser/'postgres' account ''' self.roleProvider.syncSTDMRoles() # Update view self.loadRoles() # Reset role description label self.lblRoleDescription.setText("") def sortUsers(self): ''' Sort users in ascending order ''' self.usersModel.sort(0, Qt.AscendingOrder) def sortRoles(self): ''' Sorts the roles in ascending order ''' self.rolesModel.sort(0, Qt.AscendingOrder) def onNewRole(self): ''' Slot for creating new role ''' frmNewRole = newRoleDlg(self) result = frmNewRole.exec_() if result == QDialog.Accepted: role = frmNewRole.role # Add new role to roles view numRoles = self.rolesModel.rowCount() self.rolesModel.insertRows(numRoles, 1) index = self.rolesModel.index(numRoles) self.rolesModel.setData(index, role.name) # Sort model contents self.sortRoles() def onRoleSelected(self, index): ''' Slot activated when a role item in the view is selected to load the description text. ''' roleName = index.data() role = self.roleProvider.GetRole(roleName) if role != None: self.lblRoleDescription.setText(role.description) def onDeleteRole(self): ''' Slot for deleting the selected role ''' selItems = self.lstRoles.selectionModel().selectedRows() if len(selItems) == 0: msg = QApplication.translate("manageAccountsDlg", "Please select a role to delete.") QMessageBox.warning(self, QApplication.translate("manageAccountsDlg", "Select Role"), msg) return # Get role from the first item in the selection roleIndex = selItems[0] rolename = roleIndex.data() msg = QApplication.translate("manageAccountsDlg", "Are you sure you want to delete '%s'?\nOnce deleted, this role cannot be recovered." % ( rolename,)) result = QMessageBox.warning(self, QApplication.translate("manageAccountsDlg", "Delete Role"), msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if result == QMessageBox.Yes: # Delete the role self.roleProvider.DeleteSTDMRole(rolename) self.roleProvider.DeleteRole(rolename) # Remove user from the list and role mappings view self.rolesModel.removeRows(roleIndex.row(), 1) self.lblRoleDescription.setText("") self.sortRoles() def loadUserMappings(self, rolename=""): ''' Loads checked/unchecked users in the user mappings list based on whether they are non/members of the specified group. If rolename is empty, then just load all users with the check state set to 'Unchecked' ''' roleUsers = [] if rolename != "": roleUsers = self.roleProvider.GetUsersInRole(rolename) sysUsers = self.usersModel._users # Initialize model self.UserMappingsModel = QStandardItemModel(len(sysUsers), 1, self) # Create standard user items (checkable and with an icon) then add them to the list view for u in range(len(sysUsers)): user = sysUsers[u] userItem = self._createNewUserMapping(user) # If the user is in the given role then set checkstate to 'checked' sysIndex = getIndex(roleUsers, user) if sysIndex != -1: userItem.setCheckState(Qt.Checked) self.UserMappingsModel.setItem(u, userItem) self.lstMappingUsers.setModel(self.UserMappingsModel) def _createNewUserMapping(self, username): ''' Adds a new user to the list of user mappings ''' # Set icon icon = QIcon() icon.addPixmap(GuiUtils.get_icon_pixmap("user.png"), QIcon.Normal, QIcon.Off) userItem = QStandardItem(icon, username) userItem.setCheckable(True) userItem.setCheckState(Qt.Unchecked) return userItem def onRoleMappingSelected(self, index): ''' Slot activated when a role item in the mapping view is selected to load the users in the specified role ''' self.lstMappingUsers.setEnabled(True) roleName = index.data() self.currentRole = roleName self.loadUserMappings(roleName) def onUserMappingSelected(self, index): ''' Slot which is called when a user item in the user mapping list has been clicked or selected to add it to the currently selected role ''' if self.currentRole != None: item = self.UserMappingsModel.itemFromIndex(index) username = item.text() self.blockSignals(True) # Add user to role if the item is selected or remove if it was checked if item.checkState() == Qt.Checked: self.roleProvider.AddUsersToRoles([username], [self.currentRole]) elif item.checkState() == Qt.Unchecked: self.roleProvider.RemoveUsersFromRoles([username], [self.currentRole]) self.blockSignals(False)
class AdjustmentDialogThresholds(QObject): COLOR_ERROR = QColor(224, 103, 103) COLOR_ATTENTION = QColor(237, 148, 76) COLOR_NEUTRAL = QColor(255, 255, 255) COLOR = {1: COLOR_NEUTRAL, 2: COLOR_ATTENTION, 3: COLOR_ERROR} sig_clickedRow = pyqtSignal(int) def __init__(self, parent, datasetSize): """ :type parent: gui.adjustmentDialog.AdjustmentDialog """ super().__init__() self.parent = parent self.tbl = self.parent.tableThresholds self.model = QStandardItemModel(datasetSize[0], datasetSize[1], self.tbl) self.initState = True self.thresholdExeeded = False self.tbl.setModel(self.model) self.tbl.resizeColumnsToContents() self.tbl.resizeRowsToContents() # Icons self.iconOk = QIcon() self.iconOk.addPixmap( QPixmap(":/plugins/SeilaplanPlugin/gui/icons/icon_green.png"), QIcon.Normal, QIcon.Off) self.iconErr = QIcon() self.iconErr.addPixmap( QPixmap( ":/plugins/SeilaplanPlugin/gui/icons/icon_exclamation.png"), QIcon.Normal, QIcon.Off) self.tbl.clicked.connect(self.onClick) def populate(self, header, dataset, valueColumn): self.model.setHorizontalHeaderLabels(header) self.tbl.hideColumn(5) # Insert data into cells for i, rowData in enumerate(dataset): for j, cellData in enumerate(rowData): if j == 0: # Create clickable info button in first column btnWidget = self.createInfoBtn(cellData) self.tbl.setIndexWidget(self.model.index(i, j), btnWidget) continue if j == 5 and isinstance(cellData, dict): loclen = len(cellData['loc']) if loclen > 0: # Set background color for cells where threshold is # exceeded color = self.COLOR[max(cellData['color'] or [1])] self.colorBackground(i, valueColumn, color) cellData = loclen item = QStandardItem(cellData) self.model.setItem(i, j, item) self.model.setData(self.model.index(i, j), cellData) # Adjust column widths self.tbl.resizeColumnsToContents() for idx in range(2, self.model.columnCount()): currSize = self.tbl.sizeHintForColumn(idx) self.tbl.setColumnWidth(idx, max(currSize, 100)) self.tbl.setFocusPolicy(Qt.NoFocus) self.updateTabIcon() def updateData(self, row, col, newVal): # Update background color of new values if col == 5 and isinstance(newVal, dict): locLen = len(newVal['loc']) color = self.COLOR[max(newVal['color'] or [1])] self.colorBackground(row, 4, color) newVal = locLen # Update value itself self.model.setData(self.model.index(row, col), newVal) self.updateTabIcon() # Remove the background color from initially calculated # cable line data if self.initState: self.initState = False for row in range(self.model.rowCount()): self.colorBackground(row, 3, self.COLOR_NEUTRAL) def colorBackground(self, row, col, color): self.model.setData(self.model.index(row, col), QBrush(color), Qt.BackgroundRole) def updateTabIcon(self): """ Updates icon of QTabWidget with an exclamation mark or check mark depending on presents of exceeded thresholds.""" thresholdExceeded = False for i in range(0, self.model.rowCount()): if i == 2: # Dont check thresholds for 'Sattelkraft' continue data = self.model.data(self.model.index(i, 5)) if data and data > 0: thresholdExceeded = True break if thresholdExceeded: self.parent.tabWidget.setTabIcon(2, self.iconErr) else: self.parent.tabWidget.setTabIcon(2, self.iconOk) def onClick(self, item): # Row is already selected if self.parent.selectedThdRow == item.row(): # Deselect self.tbl.clearSelection() # Emit select signal self.sig_clickedRow.emit(item.row()) def createInfoBtn(self, cellData): button = QPushButton('?') button.setMaximumSize(QSize(22, 22)) # Fill info text into message box button.clicked.connect( lambda: QMessageBox.information(self.parent, cellData[ 'title'], cellData['message'], QMessageBox.Ok)) cellWidget = QWidget() # Add layout to center button in cell layout = QHBoxLayout(cellWidget) layout.addWidget(button, 0, Qt.AlignCenter) layout.setAlignment(Qt.AlignCenter) cellWidget.setLayout(layout) return cellWidget