def addObjToForm(obj, feature): ''' used to populate the update form and 2x Queue Views obj = form or widget feature == the aims feature ''' obj.uAddressType.setCurrentIndex(QComboBox.findText(obj.uAddressType, obj.feature._addressType)) obj.uExternalAddId.setText(UiUtility.nullEqualsNone(obj.feature._externalAddressId)) obj.uExternalAddressIdScheme.setText(UiUtility.nullEqualsNone(obj.feature._externalAddressIdScheme)) obj.ulifeCycle.setCurrentIndex(QComboBox.findText(obj.ulifeCycle, obj.feature._lifecycle)) obj.uUnitType.setCurrentIndex(QComboBox.findText(obj.uUnitType, obj.feature._unitType)) obj.uUnit.setText(UiUtility.nullEqualsNone(obj.feature._unitValue)) obj.uLevelType.setCurrentIndex(QComboBox.findText(obj.uLevelType, obj.feature._levelType)) obj.uLevelValue.setText(UiUtility.nullEqualsNone(obj.feature._levelValue)) obj.uPrefix.setText(UiUtility.nullEqualsNone(obj.feature._addressNumberPrefix)) obj.uBase.setText(UiUtility.nullEqualsNone(obj.feature._addressNumber)) obj.uAlpha.setText(UiUtility.nullEqualsNone(obj.feature._addressNumberSuffix)) obj.uHigh.setText(UiUtility.nullEqualsNone(obj.feature._addressNumberHigh)) obj.uRoadCentrelineId.setText(UiUtility.nullEqualsNone(obj.feature._roadCentrelineId)) obj.uRoadPrefix.setText(UiUtility.nullEqualsNone(obj.feature._roadPrefix)) obj.uRoadName.setText(UiUtility.nullEqualsNone(obj.feature._roadName)) obj.uRoadTypeName.setText(UiUtility.nullEqualsNone(obj.feature._roadType)) obj.uRoadSuffix.setText(UiUtility.nullEqualsNone(obj.feature._roadSuffix)) obj.uWaterRouteName.setText(UiUtility.nullEqualsNone(obj.feature._waterRoute)) obj.uWaterName.setText(UiUtility.nullEqualsNone(obj.feature._waterName)) # addressable object obj.uObjectType.setCurrentIndex(QComboBox.findText(obj.uObjectType, obj.feature._aoType)) obj.uObjectName.setText(UiUtility.nullEqualsNone(obj.feature._aoName)) obj.uExternalObjectId.setText(UiUtility.nullEqualsNone(obj.feature._externalObjectId)) obj.uExtObjectIdScheme.setText(UiUtility.nullEqualsNone(obj.feature._externalObjectIdScheme)) obj.uValuationReference.setText(UiUtility.nullEqualsNone(obj.feature._valuationReference)) obj.uCertificateOfTitle.setText(UiUtility.nullEqualsNone(obj.feature._certificateOfTitle)) obj.uAppellation.setText(UiUtility.nullEqualsNone(obj.feature._appellation)) from QueueEditorWidget import QueueEditorWidget if isinstance(obj, QueueEditorWidget): pass
class EnumConfigControl(ConfigControl): def __init__(self, config_item): ConfigControl.__init__(self, config_item) self._init_ui() def _init_ui(self): lbl_enum = QLabel(self._config_item.tag()) lbl_enum.setFixedWidth(self.LABEL_WIDTH) self._cmbo_enum = QComboBox() self._cmbo_enum.addItems(self._config_item.enum_names) selected = self._config_item.value() index = self._cmbo_enum.findText(selected, QtCore.Qt.MatchFixedString) self._cmbo_enum.setCurrentIndex(index) hbox = QHBoxLayout() hbox.setContentsMargins(0, 0, 0, 0) hbox.addWidget(lbl_enum) hbox.addWidget(self._cmbo_enum) hbox.addStretch() self.setLayout(hbox) def update_from_config(self): selected = self._config_item.value() index = self._cmbo_enum.findText(selected, QtCore.Qt.MatchFixedString) index = max(0, index) self._cmbo_enum.setCurrentIndex(index) def save_to_config(self): value = self._cmbo_enum.currentText() self._config_item.set(value)
class ProjectData(QWidget): def __init__(self, parent): super(ProjectData, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(self.tr("Name:")), 0, 0) self.name = QLineEdit() if self._parent._item.name == '': self.name.setText(file_manager.get_basename( self._parent._item.path)) else: self.name.setText(self._parent._item.name) grid.addWidget(self.name, 0, 1) grid.addWidget(QLabel(self.tr("Project Type:")), 1, 0) self.txtType = QLineEdit() completer = QCompleter(sorted(settings.PROJECT_TYPES)) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.txtType.setCompleter(completer) self.txtType.setText(self._parent._item.projectType) grid.addWidget(self.txtType, 1, 1) grid.addWidget(QLabel(self.tr("Description:")), 2, 0) self.description = QPlainTextEdit() self.description.setPlainText(self._parent._item.description) grid.addWidget(self.description, 2, 1) grid.addWidget(QLabel(self.tr("URL:")), 3, 0) self.url = QLineEdit() self.url.setText(self._parent._item.url) grid.addWidget(self.url, 3, 1) grid.addWidget(QLabel(self.tr("Licence:")), 4, 0) self.cboLicense = QComboBox() self.cboLicense.addItem('Apache License 2.0') self.cboLicense.addItem('Artistic License/GPL') self.cboLicense.addItem('Eclipse Public License 1.0') self.cboLicense.addItem('GNU General Public License v2') self.cboLicense.addItem('GNU General Public License v3') self.cboLicense.addItem('GNU Lesser General Public License') self.cboLicense.addItem('MIT License') self.cboLicense.addItem('Mozilla Public License 1.1') self.cboLicense.addItem('New BSD License') self.cboLicense.addItem('Other Open Source') self.cboLicense.addItem('Other') self.cboLicense.setCurrentIndex(4) index = self.cboLicense.findText(self._parent._item.license) self.cboLicense.setCurrentIndex(index) grid.addWidget(self.cboLicense, 4, 1) self.txtExtensions = QLineEdit() self.txtExtensions.setText(', '.join(self._parent._item.extensions)) grid.addWidget(QLabel(self.tr("Supported Extensions:")), 5, 0) grid.addWidget(self.txtExtensions, 5, 1) grid.addWidget(QLabel(self.tr("Indentation: ")), 6, 0) self.spinIndentation = QSpinBox() self.spinIndentation.setValue(self._parent._item.indentation) self.spinIndentation.setMinimum(1) grid.addWidget(self.spinIndentation, 6, 1) self.checkUseTabs = QCheckBox(self.tr("Use Tabs.")) self.checkUseTabs.setChecked(self._parent._item.useTabs) grid.addWidget(self.checkUseTabs, 6, 2)
class GoogleFinanceUrlSetupDialog(QDialog): SETTING_GOOGLE_URL = 'googleUrl' SETTING_GOOGLE_COUNTRY = 'googleCountry' def __init__(self, parent): QDialog.__init__(self, parent) self.prop = MaeMoneyProperties.instance() self.urls = {} self.urls[self.prop.GOOGLE_COUNTRY_HK] = 'www.google.com.hk' self.urls[self.prop.GOOGLE_COUNTRY_CN] = 'www.google.com.cn' self.urls[self.prop.GOOGLE_COUNTRY_CAN] = 'www.google.ca' self.urls[self.prop.GOOGLE_COUNTRY_UK] = 'www.google.co.uk' self.urls[self.prop.GOOGLE_COUNTRY_US] = 'www.google.com' self.setupUi() def setupUi(self): self.setWindowModality(Qt.WindowModal) self.buttonBox = QDialogButtonBox(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.gridLayout = QGridLayout() self.setLayout(self.gridLayout) self.labelGFinanceUrl = QLabel(self.tr("Google URL")) self.gridLayout.addWidget(self.labelGFinanceUrl, 0, 1, 1, 1) self.comboBoxGFinanceUrl = QComboBox() for [country, url] in sorted(self.urls.iteritems()): self.comboBoxGFinanceUrl.addItem(country, url) googleCountry = self.prop.getGoogleCountry() index = self.comboBoxGFinanceUrl.findText(googleCountry) self.comboBoxGFinanceUrl.setCurrentIndex(index) self.gridLayout.addWidget(self.comboBoxGFinanceUrl, 0, 2, 1, 1) self.gridLayout.addWidget(QLabel(self.tr("Current setting")), 1, 1, 1, 1) self.gridLayout.addWidget(QLabel(self.prop.getGoogleCountry()), 1, 2, 1, 1) self.setUrlButton = QPushButton(self.tr("Set URL")) self.gridLayout.addWidget(self.setUrlButton, 2, 1, 1, 2) self.loginErrorMsgLabel = QLabel("") self.gridLayout.addWidget(self.loginErrorMsgLabel, 3, 1, 1, 2) self.setWindowTitle(self.tr("Setup")) self.connect(self.buttonBox, SIGNAL("accepted()"), self.accept) self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject) self.connect(self.setUrlButton, SIGNAL("clicked()"), self.setUrl) def setUrl(self): indexSelected = self.comboBoxGFinanceUrl.currentIndex() country = self.comboBoxGFinanceUrl.itemText(indexSelected) url = self.comboBoxGFinanceUrl.itemData(indexSelected).toString().toAscii() self.prop.setGoogleCountryUrl(country, url) self.accept()
def __init__(self, game): SelectRuleset.__init__(self) self.game = game Players.load() self.setWindowTitle(m18n('Select four players') + ' - Kajongg') self.names = None self.nameWidgets = [] for idx, wind in enumerate(WINDS): cbName = QComboBox() cbName.manualSelect = False # increase width, we want to see the full window title cbName.setMinimumWidth(350) # is this good for all platforms? cbName.addItems(Players.humanNames.values()) self.grid.addWidget(cbName, idx+1, 1) self.nameWidgets.append(cbName) self.grid.addWidget(WindLabel(wind), idx+1, 0) cbName.currentIndexChanged.connect(self.slotValidate) query = Query("select p0,p1,p2,p3 from game where seed is null and game.id = (select max(id) from game)") if len(query.records): for pidx, playerId in enumerate(query.records[0]): try: playerName = Players.humanNames[playerId] cbName = self.nameWidgets[pidx] playerIdx = cbName.findText(playerName) if playerIdx >= 0: cbName.setCurrentIndex(playerIdx) except KeyError: logError('database is inconsistent: player with id %d is in game but not in player' \ % playerId) self.slotValidate()
def lineEditor(self, name, item, props, parent): """ Creates a new editor suitable for selecting a series or index. @param name item parameter name, as string, to receive value updates @param item IndexItem instance @param props mapping of index class constructor properties @param parent ancestor of new widget @return QComboBox widget """ children = list(item.root().children(True)) editor = QComboBox(parent) editor.addItem('') exclude = [item.text(), self.defaultText] items = [c.text() for c in children if c.text() not in exclude] editor.addItems(items) try: editor.setCurrentIndex(editor.findText(item.parameters[name])) except (KeyError, ): item.parameters[name] = '' @pyqtSignature('int') def onChange(index): item.parameters[name] = str(editor.currentText()) self.emit(Signals.modified) editor.onChange = onChange editor.connect(editor, Signals.currentIndexChanged, onChange) return editor
def __init__(self, game): SelectRuleset.__init__(self) self.game = game Players.load() self.setWindowTitle(m18n('Select four players') + ' - Kajongg') self.names = None self.nameWidgets = [] for idx, wind in enumerate(WINDS): cbName = QComboBox() cbName.manualSelect = False # increase width, we want to see the full window title cbName.setMinimumWidth(350) # is this good for all platforms? cbName.addItems(Players.humanNames.values()) self.grid.addWidget(cbName, idx + 1, 1) self.nameWidgets.append(cbName) self.grid.addWidget(WindLabel(wind), idx + 1, 0) cbName.currentIndexChanged.connect(self.slotValidate) query = Query( "select p0,p1,p2,p3 from game where seed is null and game.id = (select max(id) from game)" ) if len(query.records): for pidx, playerId in enumerate(query.records[0]): try: playerName = Players.humanNames[playerId] cbName = self.nameWidgets[pidx] playerIdx = cbName.findText(playerName) if playerIdx >= 0: cbName.setCurrentIndex(playerIdx) except KeyError: logError('database is inconsistent: player with id %d is in game but not in player' \ % playerId) self.slotValidate()
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)
class ProjectData(QWidget): def __init__(self, parent): super(ProjectData, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(translations.TR_PROJECT_NAME), 0, 0) self.name = QLineEdit() if not len(self._parent.project.name): self.name.setText(file_manager.get_basename( self._parent.project.path)) else: self.name.setText(self._parent.project.name) grid.addWidget(self.name, 0, 1) grid.addWidget(QLabel(translations.TR_PROJECT_LOCATION), 1, 0) self.txtPath = QLineEdit() self.txtPath.setReadOnly(True) self.txtPath.setText(self._parent.project.path) grid.addWidget(self.txtPath, 1, 1) grid.addWidget(QLabel(translations.TR_PROJECT_TYPE), 2, 0) self.txtType = QLineEdit() completer = QCompleter(sorted(settings.PROJECT_TYPES)) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.txtType.setCompleter(completer) self.txtType.setText(self._parent.project.project_type) grid.addWidget(self.txtType, 2, 1) grid.addWidget(QLabel(translations.TR_PROJECT_DESCRIPTION), 3, 0) self.description = QPlainTextEdit() self.description.setPlainText(self._parent.project.description) grid.addWidget(self.description, 3, 1) grid.addWidget(QLabel(translations.TR_PROJECT_URL), 4, 0) self.url = QLineEdit() self.url.setText(self._parent.project.url) self.url.setPlaceholderText('https://www.{}.com'.format(getuser())) grid.addWidget(self.url, 4, 1) grid.addWidget(QLabel(translations.TR_PROJECT_LICENSE), 5, 0) self.cboLicense = QComboBox() self.cboLicense.addItems(LICENCES) self.cboLicense.setCurrentIndex(12) index = self.cboLicense.findText(self._parent.project.license) self.cboLicense.setCurrentIndex(index) grid.addWidget(self.cboLicense, 5, 1) self.txtExtensions = QLineEdit() self.txtExtensions.setText(', '.join(self._parent.project.extensions)) grid.addWidget(QLabel(translations.TR_PROJECT_EXTENSIONS), 6, 0) grid.addWidget(self.txtExtensions, 6, 1) grid.addWidget(QLabel(translations.TR_PROJECT_INDENTATION), 7, 0) self.spinIndentation = QSpinBox() self.spinIndentation.setValue(self._parent.project.indentation) self.spinIndentation.setRange(2, 10) self.spinIndentation.setValue(4) self.spinIndentation.setSingleStep(2) grid.addWidget(self.spinIndentation, 7, 1) self.checkUseTabs = QCheckBox(translations.TR_PROJECT_USE_TABS) self.checkUseTabs.setChecked(self._parent.project.use_tabs) grid.addWidget(self.checkUseTabs, 7, 2)
class ProjectData(QWidget): def __init__(self, parent): super(ProjectData, self).__init__() self._parent = parent grid = QGridLayout(self) grid.addWidget(QLabel(translations.TR_PROJECT_NAME), 0, 0) self.name = QLineEdit() if not len(self._parent.project.name): self.name.setText( file_manager.get_basename(self._parent.project.path)) else: self.name.setText(self._parent.project.name) grid.addWidget(self.name, 0, 1) grid.addWidget(QLabel(translations.TR_PROJECT_LOCATION), 1, 0) self.txtPath = QLineEdit() self.txtPath.setReadOnly(True) self.txtPath.setText(self._parent.project.path) grid.addWidget(self.txtPath, 1, 1) grid.addWidget(QLabel(translations.TR_PROJECT_TYPE), 2, 0) self.txtType = QLineEdit() completer = QCompleter(sorted(settings.PROJECT_TYPES)) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.txtType.setCompleter(completer) self.txtType.setText(self._parent.project.project_type) grid.addWidget(self.txtType, 2, 1) grid.addWidget(QLabel(translations.TR_PROJECT_DESCRIPTION), 3, 0) self.description = QPlainTextEdit() self.description.setPlainText(self._parent.project.description) grid.addWidget(self.description, 3, 1) grid.addWidget(QLabel(translations.TR_PROJECT_URL), 4, 0) self.url = QLineEdit() self.url.setText(self._parent.project.url) self.url.setPlaceholderText('https://www.{}.com'.format(getuser())) grid.addWidget(self.url, 4, 1) grid.addWidget(QLabel(translations.TR_PROJECT_LICENSE), 5, 0) self.cboLicense = QComboBox() self.cboLicense.addItems(LICENCES) self.cboLicense.setCurrentIndex(12) index = self.cboLicense.findText(self._parent.project.license) self.cboLicense.setCurrentIndex(index) grid.addWidget(self.cboLicense, 5, 1) self.txtExtensions = QLineEdit() self.txtExtensions.setText(', '.join(self._parent.project.extensions)) grid.addWidget(QLabel(translations.TR_PROJECT_EXTENSIONS), 6, 0) grid.addWidget(self.txtExtensions, 6, 1) grid.addWidget(QLabel(translations.TR_PROJECT_INDENTATION), 7, 0) self.spinIndentation = QSpinBox() self.spinIndentation.setValue(self._parent.project.indentation) self.spinIndentation.setRange(2, 10) self.spinIndentation.setValue(4) self.spinIndentation.setSingleStep(2) grid.addWidget(self.spinIndentation, 7, 1) self.checkUseTabs = QCheckBox(translations.TR_PROJECT_USE_TABS) self.checkUseTabs.setChecked(self._parent.project.use_tabs) grid.addWidget(self.checkUseTabs, 7, 2)
def _create_dropdownbox(self, key, value): # atomic_widget = QWidget() row, col = self.__calculate_new_grid_position() # layout = QBoxLayout(self.horizontal) atomic_widget = QComboBox() # atomic_widget.addItem("C") # atomic_widget.addItem("C++") values = self.dropdownboxes[key] # values = self.dropdownboxes[key][0] if value is not None and value in values: # vali = atomic_widget.findText(value) atomic_widget.findText(value) atomic_widget.addItems(values) # this does not work. I used findText() # atomic_widget.setCurrentIndex(vali) # layout.addWidget(cb) # atomic_widget.setLayout(layout) return atomic_widget
class resampleDialog(QDialog): def __init__(self, parent, multipleSelection, currSampRate): QDialog.__init__(self, parent) self.currLocale = self.parent().prm['data']['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) grid = QGridLayout() n = 0 if multipleSelection == False: currSampRateLabel = QLabel(self.currLocale.toString(currSampRate)) grid.addWidget(currSampRateLabel, n, 0) n = n+1 newSampRateLabel = QLabel(self.tr('New Sampling Rate: ')) grid.addWidget(newSampRateLabel, n, 0) self.newSampRateWidget = QLineEdit('48000') self.newSampRateWidget.setValidator(QIntValidator(self)) grid.addWidget(self.newSampRateWidget, n, 1) self.newSampRateWidget.editingFinished.connect(self.onSampRateChanged) n = n+1 convertorLabel = QLabel(self.tr('Resampling Algorithm: ')) grid.addWidget(convertorLabel, n, 0) self.convertorChooser = QComboBox() self.convertorChooser.addItems(['fourier']) self.convertorChooser.setCurrentIndex(0) grid.addWidget(self.convertorChooser, n, 1) n = n+1 winLabel = QLabel(self.tr('Window Type: ')) grid.addWidget(winLabel, n, 0) self.winChooser = QComboBox() self.winChooser.addItems(self.parent().prm['data']['available_windows']) self.winChooser.setCurrentIndex(self.winChooser.findText(self.parent().prm['pref']['smoothingWindow'])) grid.addWidget(self.winChooser, n, 1) n = n+1 buttonBox = QDialogButtonBox(QDialogButtonBox.Ok| QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) grid.addWidget(buttonBox, n, 1) self.setLayout(grid) self.setWindowTitle(self.tr("Resample")) def onSampRateChanged(self): newSampRate = int(self.newSampRateWidget.text()) if newSampRate < 1: QMessageBox.warning(self, self.tr('Warning'), self.tr('New sampling rate too small')) else: self.newSampRate = newSampRate
class AppLocaleSetupDialog(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.prop = MaeMoneyProperties.instance() self.locales = {} self.locales[self.prop.LANGUAGE_ZH_CN] = self.prop.LOCALE_ZH_CN self.locales[self.prop.LANGUAGE_ZH_HK] = self.prop.LOCALE_ZH_HK self.locales[self.prop.LANGUAGE_EN_US] = self.prop.LOCALE_EN_US self.setupUi() def setupUi(self): self.setWindowModality(Qt.WindowModal) self.buttonBox = QDialogButtonBox(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.gridLayout = QGridLayout() self.setLayout(self.gridLayout) self.labelAppLocale = QLabel(u"語言 Language") self.gridLayout.addWidget(self.labelAppLocale, 0, 1, 1, 1) self.comboBoxAppLocale = QComboBox() for [lang, appLocale] in sorted(self.locales.iteritems()): self.comboBoxAppLocale.addItem(lang, appLocale) language = self.prop.getAppLanguage() index = self.comboBoxAppLocale.findText(language) self.comboBoxAppLocale.setCurrentIndex(index) self.gridLayout.addWidget(self.comboBoxAppLocale, 0, 2, 1, 1) self.gridLayout.addWidget(QLabel(self.tr("Current setting")), 1, 1, 1, 1) self.gridLayout.addWidget(QLabel(self.prop.getAppLanguage()), 1, 2, 1, 1) self.setLanguageButton = QPushButton(self.tr("Set language")) self.gridLayout.addWidget(self.setLanguageButton, 2, 1, 1, 2) self.setWindowTitle(self.tr("Language setup")) self.connect(self.buttonBox, SIGNAL("accepted()"), self.accept) self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject) self.connect(self.setLanguageButton, SIGNAL("clicked()"), self.setLanguage) def setLanguage(self): indexSelected = self.comboBoxAppLocale.currentIndex() locale = self.comboBoxAppLocale.itemData(indexSelected) self.prop.setAppLocale(locale) self.accept()
class FontLayout(QGridLayout): """Font selection""" def __init__(self, value, parent=None): QGridLayout.__init__(self) font = tuple_to_qfont(value) assert font is not None # Font family self.family = QFontComboBox(parent) self.addWidget(self.family, 0, 0, 1, -1) # Font size self.size = QComboBox(parent) self.size.setEditable(True) sizelist = list(range(6, 12)) + list(range(12, 30, 2)) + [36, 48, 72] size = font.pointSize() if size not in sizelist: sizelist.append(size) sizelist.sort() self.size.addItems([str(s) for s in sizelist]) self.addWidget(self.size, 1, 0) # Italic or not self.italic = QCheckBox(self.tr("Italic"), parent) self.addWidget(self.italic, 1, 1) # Bold or not self.bold = QCheckBox(self.tr("Bold"), parent) self.addWidget(self.bold, 1, 2) self.set_font(font) def set_font(self, font): self.family.setCurrentFont(font) size = font.pointSize() i = self.size.findText(str(size)) if i >= 0: self.size.setCurrentIndex(i) self.italic.setChecked(font.italic()) self.bold.setChecked(font.bold()) def get_font(self): font = self.family.currentFont() font.setItalic(self.italic.isChecked()) font.setBold(self.bold.isChecked()) font.setPointSize(int(self.size.currentText())) return qfont_to_tuple(font)
class EkdStylePropertie(EkdPropertie): """ Définition de la propriété correspondant à un QStyle """ def __init__(self, prop, name, value, choices=[], section=None ): super(EkdStylePropertie, self).__init__(prop, name, value, EkdPropertie.STYLE, section) self.label = QLabel(name) self.widget = QComboBox() self.widget.addItems(choices) self.widget.setCurrentIndex(self.widget.findText(value)) # Quand on change de codec, on met à jour EkdConfig self.connect(self.widget, SIGNAL("currentIndexChanged(int)"), self.updateStyle) def updateStyle(self): self.value = self.widget.currentText() EkdConfig.set(self.section, self.id, self.value)
class VectorPage(QWidget): def __init__(self, parent=None, filters="", encodings=[]): QWidget.__init__(self, parent) self.filters = filters self.layerLineEdit = QLineEdit() self.browseToolButton = QToolButton() self.browseToolButton.setAutoRaise(True) self.browseToolButton.setIcon(QIcon(":document-open")) layerLabel = QLabel("&Dataset:") layerLabel.setBuddy(self.layerLineEdit) self.encodingComboBox = QComboBox() self.encodingComboBox.addItems(encodings) encodingLabel = QLabel("&Encoding:") encodingLabel.setBuddy(self.encodingComboBox) hbox = QHBoxLayout() hbox.addWidget(layerLabel) hbox.addWidget(self.layerLineEdit) hbox.addWidget(self.browseToolButton) vbox = QVBoxLayout() vbox.addLayout(hbox) hbox = QHBoxLayout() hbox.addWidget(encodingLabel) hbox.addWidget(self.encodingComboBox) vbox.addLayout(hbox) self.setLayout(vbox) self.encodingComboBox.setCurrentIndex(self.encodingComboBox.findText("System")) self.connect(self.browseToolButton, SIGNAL("clicked()"), self.browseToFile) self.connect(self.encodingComboBox, SIGNAL("currentIndexChanged(QString)"), self.changeEncoding) def browseToFile(self): dialog = QFileDialog(self, "manageR - Open Vector File", unicode(robjects.r.getwd()[0]), self.filters) if not dialog.exec_() == QDialog.Accepted: return files = dialog.selectedFiles() file = files.first().trimmed() self.layerLineEdit.setText(file) self.emit(SIGNAL("filePathChanged(QString)"), file) def changeEncoding(self, text): self.emit(SIGNAL("encodingChanged(QString)"), text)
class QuickWatch(QToolBar): def __init__(self, parent, distributedObjects): QToolBar.__init__(self, "QuickWatch") self.config = QuickWatchConfig() distributedObjects.configStore.registerConfigSet(self.config) self.setObjectName("QuickWatch") parent.addToolBar(self) self.watchedit = QComboBox() self.watchedit.setFixedHeight(28) self.watchedit.setInsertPolicy(QComboBox.NoInsert) self.watchedit.setEditable(True) self.watchedit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.addWidget(self.watchedit) self.distributedObjects = distributedObjects self.addAction(Icons.watch, "Add to Watch", self.addToWatch) self.addAction(Icons.datagraph, "Add to Data Graph", self.addToDG) self.watchedit.lineEdit().returnPressed.connect(self.returnPressed) def __addCurrentText(self): text = self.watchedit.lineEdit().text() idx = self.watchedit.findText(text) if idx == -1: self.watchedit.addItem(text) self.watchedit.setEditText("") def returnPressed(self): if self.config.addTo.value == "Watch View": self.addToWatch() elif self.config.addTo.value == "Data Graph View": self.addToDG() def addToWatch(self): self.distributedObjects.watchModel.addVar( self.watchedit.lineEdit().text()) self.__addCurrentText() def addToDG(self): self.distributedObjects.datagraphController.addWatch( self.watchedit.lineEdit().text()) self.__addCurrentText()
class changeChannelDialog(QDialog): def __init__(self, parent, multipleSelection, currChan): QDialog.__init__(self, parent) grid = QGridLayout() n = 0 chooserLabel = QLabel(self.tr('Channel: ')) self.chooser = QComboBox() self.chooser.addItems([self.tr('Right'), self.tr('Left')]) self.chooser.setCurrentIndex(self.chooser.findText(currChan)) grid.addWidget(self.chooser, n, 1) n = n + 1 buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) grid.addWidget(buttonBox, n, 1) self.setLayout(grid) self.setWindowTitle(self.tr("Change Channel"))
def createEditor( self, parent, option, index ): """ Creates the QComboBox widget to use when editing department selections :param parent: :type <QWidget>: :param option: :type <QStyleOptionViewItem>: :param index: :type <QModelIndex>: """ if ( not index.isValid() ): return False editor = QComboBox(parent) editor.addItems( settings.enabledDepartments() ) editor.setCurrentIndex( editor.findText( index.data( Qt.DisplayRole ).toString() ) ) return editor
class CharColumnConfigurationWidget(QWidget, columnproviders.AbstractColumnConfigurationWidget): def __init__(self, parent, hex_widget, column): QWidget.__init__(self, parent) columnproviders.AbstractColumnConfigurationWidget.__init__(self) self.hexWidget = hex_widget self.columnModel = column self.setLayout(QFormLayout()) self.layout().setContentsMargins(0, 0, 0, 0) self.cmbEncoding = QComboBox(self) self.cmbEncoding.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.layout().addRow(utils.tr('Encoding:'), self.cmbEncoding) for encoding in sorted(encodings.encodings.keys()): self.cmbEncoding.addItem(encoding) if column is not None and column.codec.name.lower() == encoding.lower(): self.cmbEncoding.setCurrentIndex(self.cmbEncoding.count() - 1) if column is None: self.cmbEncoding.setCurrentIndex(self.cmbEncoding.findText('Windows-1251')) self.spnBytesOnRow = QSpinBox(self) self.spnBytesOnRow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.spnBytesOnRow.setMinimum(1) self.spnBytesOnRow.setMaximum(32) self.layout().addRow(utils.tr('Bytes on row:'), self.spnBytesOnRow) if column is not None: self.spnBytesOnRow.setValue(column.bytesOnRow) else: self.spnBytesOnRow.setValue(16) def createColumnModel(self, hex_widget): model = CharColumnModel(self.hexWidget.document, encodings.getCodec(self.cmbEncoding.currentText()), self.hexWidget.font(), self.spnBytesOnRow.value()) return model def saveToColumn(self, column): column.codec = encodings.getCodec(self.cmbEncoding.currentText()) column._bytesOnRow = self.spnBytesOnRow.value() column.reset()
def generateDataTypesField(dataType=None): """ @rtype: QComboBox """ dataTypes = QComboBox() dataTypes.addItems( helper_methods.buildQStringList( ['TINYINT', 'SMALLINT', 'MEDIUMINT', 'INT', 'BIGINT', 'BIT'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems( helper_methods.buildQStringList(['FLOAT', 'DOUBLE', 'DECIMAL'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems( helper_methods.buildQStringList([ 'CHAR', 'VARCHAR', 'TINYTEXT', 'TEXT', 'MEDIUMTEXT', 'LONGTEXT' ])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems( helper_methods.buildQStringList([ 'BINARY', 'VARBINARY', 'TINYBLOB', 'BLOB', 'MEDIUMBLOB', 'LONGBLOB' ])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems( helper_methods.buildQStringList( ['DATE', 'TIME', 'YEAR', 'DATETIME', 'TIMESTAMP'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems( helper_methods.buildQStringList([ 'POINT', 'LINESTRING', 'POLYGON', 'GEOMETRY', 'MULTIPOINT', 'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION' ])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['ENUM', 'SET'])) if dataType is not None: dataTypes.setCurrentIndex(dataTypes.findText(dataType.upper())) return dataTypes
class changeChannelDialog(QDialog): def __init__(self, parent, multipleSelection, currChan): QDialog.__init__(self, parent) grid = QGridLayout() n = 0 chooserLabel = QLabel(self.tr('Channel: ')) self.chooser = QComboBox() self.chooser.addItems([self.tr('Right'), self.tr('Left')]) self.chooser.setCurrentIndex(self.chooser.findText(currChan)) grid.addWidget(self.chooser, n, 1) n = n+1 buttonBox = QDialogButtonBox(QDialogButtonBox.Ok| QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) grid.addWidget(buttonBox, n, 1) self.setLayout(grid) self.setWindowTitle(self.tr("Change Channel"))
class QuickWatch(QToolBar): def __init__(self, parent, distributedObjects): QToolBar.__init__(self, "QuickWatch") self.config = QuickWatchConfig() distributedObjects.configStore.registerConfigSet(self.config) self.setObjectName("QuickWatch") parent.addToolBar(self) self.watchedit = QComboBox() self.watchedit.setFixedHeight(28) self.watchedit.setInsertPolicy(QComboBox.NoInsert) self.watchedit.setEditable(True) self.watchedit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.addWidget(self.watchedit) self.distributedObjects = distributedObjects self.addAction(Icons.watch, "Add to Watch", self.addToWatch) self.addAction(Icons.datagraph, "Add to Data Graph", self.addToDG) self.watchedit.lineEdit().returnPressed.connect(self.returnPressed) def __addCurrentText(self): text = self.watchedit.lineEdit().text() idx = self.watchedit.findText(text) if idx == -1: self.watchedit.addItem(text) self.watchedit.setEditText("") def returnPressed(self): if self.config.addTo.value == "Watch View": self.addToWatch() elif self.config.addTo.value == "Data Graph View": self.addToDG() def addToWatch(self): self.distributedObjects.watchModel.addVar(self.watchedit.lineEdit().text()) self.__addCurrentText() def addToDG(self): self.distributedObjects.datagraphController.addWatch(self.watchedit.lineEdit().text()) self.__addCurrentText()
def __init__(self, type, parent=None): QWidget.__init__(self,parent) self.ui = gui.entityAdderUi() self.ui.setupUi(self) # only show 'cancel' button until valid name has been given self.ui.buttonBox.setStandardButtons(\ QDialogButtonBox.Cancel|QDialogButtonBox.NoButton) self.ui.formLayout.setHorizontalSpacing(120) self.ui.formLayout.setFieldGrowthPolicy(0) self.parent = parent self.type = type self.setWindowTitle("Add "+type) self.parent = parent self.names = [''] # dynamically add buttons depending on type and defined attributes if self.type == 'subject': self.attributes = parent.settings.subjectAttributes self.ui.openButton.hide() QObject.connect(self.ui.lineEdit, SIGNAL("returnPressed()"), self.submitSubject) QObject.connect(self.ui.lineEdit, SIGNAL("returnPressed()"), self.parent.refreshEntities) if self.type == 'stimulus': self.attributes = parent.settings.stimulusAttributes self.ui.label.hide() QObject.connect(self.ui.openButton, SIGNAL("clicked()"), self.selectStimulus) for (name,vals) in self.attributes: combobox = QComboBox(self) combobox.addItems(vals) combobox.setMinimumContentsLength(9) if name in self.parent.adderSettings: i = combobox.findText(self.parent.adderSettings[name]) combobox.setCurrentIndex(i) self.ui.formLayout.addRow(name, combobox) # connect buttons QObject.connect(self.ui.lineEdit, SIGNAL("textChanged(QString)"), self.enableOK) QObject.connect(self.ui.buttonBox, SIGNAL("accepted()"), self.submitEntity) QObject.connect(self.ui.buttonBox, SIGNAL("accepted()"), self.parent.refreshEntities)
def generateDataTypesField(dataType=None): """ @rtype: QComboBox """ dataTypes = QComboBox() dataTypes.addItems(helper_methods.buildQStringList(['TINYINT', 'SMALLINT', 'MEDIUMINT', 'INT', 'BIGINT', 'BIT'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['FLOAT', 'DOUBLE', 'DECIMAL'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['CHAR', 'VARCHAR', 'TINYTEXT', 'TEXT', 'MEDIUMTEXT', 'LONGTEXT'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['BINARY', 'VARBINARY', 'TINYBLOB', 'BLOB', 'MEDIUMBLOB', 'LONGBLOB'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['DATE', 'TIME', 'YEAR', 'DATETIME', 'TIMESTAMP'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['POINT', 'LINESTRING', 'POLYGON', 'GEOMETRY', 'MULTIPOINT', 'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION'])) dataTypes.insertSeparator(dataTypes.count()) dataTypes.addItems(helper_methods.buildQStringList(['ENUM', 'SET'])) if dataType is not None: dataTypes.setCurrentIndex(dataTypes.findText(dataType.upper())) return dataTypes
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
class concatenateDialog(QDialog): def __init__(self, parent, snd1, snd2): QDialog.__init__(self, parent) self.order = 'given' self.snd1 = snd1 self.snd2 = snd2 self.currLocale = self.parent().prm['data']['currentLocale'] self.currLocale.setNumberOptions( self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) grid = QGridLayout() n = 0 snd1Label = QLabel(self.tr('Sound 1: ')) grid.addWidget(snd1Label, n, 0) snd2Label = QLabel(self.tr('Sound 2: ')) grid.addWidget(snd2Label, n, 1) n = n + 1 self.snd1Widget = QLineEdit(snd1['label']) self.snd1Widget.setReadOnly(True) grid.addWidget(self.snd1Widget, n, 0) self.snd2Widget = QLineEdit(snd2['label']) self.snd2Widget.setReadOnly(True) grid.addWidget(self.snd2Widget, n, 1) swapButton = QPushButton(self.tr("Swap Sounds"), self) swapButton.clicked.connect(self.onClickSwapButton) grid.addWidget(swapButton, n, 2) n = n + 1 delayTypeLabel = QLabel(self.tr('Delay Type: ')) grid.addWidget(delayTypeLabel, n, 0) self.delayTypeChooser = QComboBox() self.delayTypeChooser.addItems(['offset to onset', 'onset to onset']) self.delayTypeChooser.setCurrentIndex(0) grid.addWidget(self.delayTypeChooser, n, 1) n = n + 1 delayLabel = QLabel(self.tr('Delay (ms): ')) grid.addWidget(delayLabel, n, 0) self.delayWidget = QLineEdit('0') self.delayWidget.setValidator(QDoubleValidator(self)) grid.addWidget(self.delayWidget, n, 1) n = n + 1 outNameLabel = QLabel(self.tr('Sound Label: ')) grid.addWidget(outNameLabel, n, 0) self.outNameWidget = QLineEdit(str(snd1['label'] + '-' + snd2['label'])) grid.addWidget(self.outNameWidget, n, 1) n = n + 1 outChanLabel = QLabel(self.tr('Output Channel: ')) grid.addWidget(outChanLabel, n, 0) self.outChanChooser = QComboBox() self.outChanChooser.addItems([self.tr('Right'), self.tr('Left')]) if snd1['chan'] == snd2['chan']: self.outChanChooser.setCurrentIndex( self.outChanChooser.findText(snd1['chan'])) else: self.outChanChooser.setCurrentIndex(0) grid.addWidget(self.outChanChooser, n, 1) n = n + 1 buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) grid.addWidget(buttonBox, n, 2) self.setLayout(grid) self.setWindowTitle(self.tr("Concatenate")) def onClickSwapButton(self): if self.order == 'given': self.order = 'swapped' self.snd1Widget.setText(self.snd2['label']) self.snd2Widget.setText(self.snd1['label']) elif self.order == 'swapped': self.order = 'given' self.snd1Widget.setText(self.snd1['label']) self.snd2Widget.setText(self.snd2['label'])
class LayerSelectionPage(QFrame): #TODO. Filtering, (visible) row selection, multi selection colparams = ((0,65,'Name'), (1,235,'Title'), (2,350,'Keywords')) XFER_BW = 40 def __init__(self, parent=None): super(LayerSelectionPage, self).__init__(parent) self.parent = parent #convenience link self.confconn_link = self.parent.parent.confconn #flag top prevent read read action on keyword delete. New logic makes this redundant #self.keywordbypass = False QToolTip.setFont(QFont('SansSerif', 10)) #label filterlabel = QLabel('Filter') availablelabel = QLabel('Available Layers') selectionlabel = QLabel('Layer Selections') keywordlabel = QLabel('Keyword') explainlabel = QLabel("Edit Group assignments using this dialog or to simply initialise the Layer-Config just click 'Finish'") #selection buttons chooseallbutton = QPushButton('>>') chooseallbutton.setFixedWidth(self.XFER_BW) chooseallbutton.clicked.connect(self.doChooseAllClickAction) choosebutton = QPushButton('>') choosebutton.setFixedWidth(self.XFER_BW) choosebutton.clicked.connect(self.doChooseClickAction) rejectbutton = QPushButton('<') rejectbutton.setFixedWidth(self.XFER_BW) rejectbutton.clicked.connect(self.doRejectClickAction) rejectallbutton = QPushButton('<<') rejectallbutton.setFixedWidth(self.XFER_BW) rejectallbutton.clicked.connect(self.doRejectAllClickAction) #operation buttons finishbutton = QPushButton('Finish') finishbutton.setToolTip('Finish and Close layer selection dialog') finishbutton.clicked.connect(self.parent.close) resetbutton = QPushButton('Reset') resetbutton.font() resetbutton.setToolTip('Read Layer from LDS GetCapabilities request. Overwrites current Layer Config') resetbutton.clicked.connect(self.doResetClickAction) self.available_sfpm = LDSSFPAvailableModel(self) self.selection_sfpm = LDSSFPSelectionModel(self) self.available_sfpm.setSourceModel(self.parent.available_model) self.selection_sfpm.setSourceModel(self.parent.selection_model) #textedits filteredit = QLineEdit('') filteredit.setToolTip('Filter Available-Layers pane (filter operates across Name and Title fields and accepts Regex expressions)') filteredit.textChanged.connect(self.available_sfpm.setActiveFilter) self.keywordcombo = QComboBox() self.keywordcombo.setToolTip('Select or Add a unique identifier to be saved in layer config (keyword)') self.keywordcombo.addItems(list(self.confconn_link.assigned)) self.keywordcombo.setEditable(True) self.keywordcombo.activated.connect(self.doKeyComboChangeAction) lgindex = self.confconn_link.getLayerGroupIndex(self.confconn_link.lgval,col=1) lgentry = self.confconn_link.lglist[lgindex] if LU.assessNone(lgindex) else None #keywordedit = self.keywordcombo.lineEdit().text().toUtf8().data().decode('utf8')# for writing #if no entry or layer indicated then blank self.keywordcombo.lineEdit().setText('' if lgentry is None or lgentry[0]==LORG.LAYER else lgentry[1])#self.confconn_link.lgval)#TODO. group only #header headmodel = QStandardItemModel() headmodel.setHorizontalHeaderLabels([i[2] for i in self.colparams][:self.parent.available_model.columnCount()]) headview1 = QHeaderView(Qt.Horizontal) headview1.setModel(headmodel) headview1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) headview2 = QHeaderView(Qt.Horizontal) headview2.setModel(headmodel) headview2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) #table self.available = QTableView() self.available.setSelectionBehavior(QAbstractItemView.SelectRows) self.available.setSelectionMode(QAbstractItemView.MultiSelection) self.selection = QTableView() self.selection.setSelectionBehavior(QAbstractItemView.SelectRows) self.selection.setSelectionMode(QAbstractItemView.MultiSelection) #interesting, must set model after selection attributes but before headers else row selections/headers don't work properly self.available.setModel(self.available_sfpm) self.selection.setModel(self.selection_sfpm) self.available.setSortingEnabled(True) self.available.setHorizontalHeader(headview1) self.selection.setSortingEnabled(True) self.selection.setHorizontalHeader(headview2) for cp in self.colparams: self.available.setColumnWidth(cp[0],cp[1]) self.selection.setColumnWidth(cp[0],cp[1]) self.available.verticalHeader().setVisible(False) self.available.horizontalHeader().setVisible(True) self.selection.verticalHeader().setVisible(False) self.selection.horizontalHeader().setVisible(True) #layout vbox00 = QVBoxLayout() vbox00.addWidget(availablelabel) vbox00.addWidget(self.available) vbox01 = QVBoxLayout() vbox01.addWidget(chooseallbutton) vbox01.addWidget(choosebutton) vbox01.addWidget(rejectbutton) vbox01.addWidget(rejectallbutton) vbox02 = QVBoxLayout() vbox02.addWidget(selectionlabel) vbox02.addWidget(self.selection) vbox10 = QVBoxLayout() vbox10.addWidget(filterlabel) vbox10.addWidget(filteredit) hbox12 = QHBoxLayout() hbox12.addWidget(keywordlabel) hbox12.addStretch(1) #hbox12.addWidget(inspbutton) #hbox12.addWidget(addbutton) #hbox12.addWidget(delbutton) vbox12 = QVBoxLayout() vbox12.addLayout(hbox12) vbox12.addWidget(self.keywordcombo) #00|01|02 #10|11|12 grid0 = QGridLayout() grid0.addLayout(vbox00,1,0) grid0.addLayout(vbox01,1,1) grid0.addLayout(vbox02,1,2) grid0.addLayout(vbox10,0,0) grid0.addLayout(vbox12,0,2) hbox2 = QHBoxLayout() hbox2.addWidget(resetbutton) hbox2.addStretch(1) hbox2.addWidget(explainlabel) hbox2.addWidget(finishbutton) #gbox1.setLayout(hbox2) vbox3 = QVBoxLayout() vbox3.addLayout(grid0) #vbox3.addLayout(hbox3) #vbox3.addWidget(line0) vbox3.addLayout(hbox2) self.setLayout(vbox3) def doChooseAllClickAction(self): '''Moves the lot to Selected''' #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data()) ktext = LU.recode(LQ.readWidgetText(self.keywordcombo.lineEdit().text())) if not self.checkKeyword(ktext): return #------------------------------ self.parent.signalModels(self.parent.STEP.PRE) #self.parent.selection_model.mdata += self.parent.available_model.mdata self.parent.selection_model.initData(self.confconn_link.complete) self.parent.available_model.initData([]) self.parent.signalModels(self.parent.STEP.POST) #------------------------------ self.parent.writeKeysToLayerConfig(ktext) #self.confconn_link.setupAssignedLayerList() if self.keywordcombo.findText(ktext) == -1: self.keywordcombo.addItem(ktext) def doChooseClickAction(self): '''Takes available selected and moves to selection''' #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data()) ktext = LU.recode(LQ.readWidgetText(self.keywordcombo.lineEdit().text())) #ktext = str(self.keywordcombo.lineEdit().text()) if not self.checkKeyword(ktext): return #------------------------------ select = self.available.selectionModel() if select.hasSelection(): self.transferSelectedRows(select.selectedRows(),self.available_sfpm,self.selection_sfpm) #------------------------------ self.parent.writeKeysToLayerConfig(ktext) #self.confconn_link.assigned = self.confconn_link.setupAssignedLayerList() # -1 to indicate no index since 0,1,... are valid if self.keywordcombo.findText(ktext) == -1: self.keywordcombo.addItem(ktext) else: ldslog.warn('L2R > Transfer action without selection') #TRACE# #pdb.set_trace() self.available.clearSelection() def transferSelectedRows(self,indices,from_model,to_model): tlist = [] for proxymodelindex in indices: transfer = from_model.getData(proxymodelindex) tlist.append((proxymodelindex,transfer),) to_model.addData([t[1] for t in tlist]) from_model.delData([t[0] for t in tlist]) return tlist def doRejectClickAction(self): '''Takes available selected and moves to selection''' #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data()) ktext = LU.recode(LQ.readWidgetText(self.keywordcombo.lineEdit().text())) if not self.checkKeyword(ktext): return #------------------------------ select = self.selection.selectionModel() if select.hasSelection(): tlist = self.transferSelectedRows(select.selectedRows(),self.selection_sfpm,self.available_sfpm) #------------------------------ kindex = self.keywordcombo.findText(ktext) remainder = self.parent.deleteKeysFromLayerConfig([ll[1][0] for ll in tlist],ktext) if remainder > 0 and kindex == -1: #items+newkey -> add self.parent.writeKeysToLayerConfig(ktext) self.keywordcombo.addItem(ktext) elif remainder == 0 and kindex > -1: #empty+oldkey -> del self.keywordcombo.removeItem(kindex) self.keywordcombo.clearEditText() else: ldslog.warn('R2L < Transfer action without selection') #TRACE# #pdb.set_trace() self.selection.clearSelection() def doRejectAllClickAction(self): #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data()) ktext = LU.recode(LQ.readWidgetText(self.keywordcombo.lineEdit().text())) if not self.checkKeyword(ktext): return #------------------------------ self.parent.deleteKeysFromLayerConfig([ll[0] for ll in self.parent.selection_model.mdata],ktext) #------------------------------ self.parent.signalModels(self.parent.STEP.PRE) #self.parent.available_model.mdata += self.parent.selection_model.mdata self.parent.available_model.initData(self.confconn_link.complete) self.parent.selection_model.initData([]) self.parent.signalModels(self.parent.STEP.POST) #------------------------------ #self.confconn_link.setupAssignedLayerList() #self.keywordbypass = True self.keywordcombo.removeItem(self.keywordcombo.findText(ktext)) self.keywordcombo.clearEditText() def doKeyComboChangeAction(self): '''Reset the available pane and if there is anything in the keyword box use this to init the selection pane''' #HACK #if self.keywordbypass: # self.keywordbypass = False # return #------------------------------ #ktext = LU.recode(self.keywordcombo.lineEdit().text().toUtf8().data()) ktext = LU.recode(LQ.readWidgetText(self.keywordcombo.lineEdit().text())) #------------------------------ av_sl = self.parent.splitData(ktext,self.confconn_link.complete) #av_sl = self.parent.splitData(ktext,self.confconn_link.complete) self.parent.signalModels(self.parent.STEP.PRE) self.parent.available_model.initData(av_sl[0]) self.parent.selection_model.initData(av_sl[1]) self.parent.signalModels(self.parent.STEP.POST) def doResetClickAction(self): '''Dumps the LC and rebuilds from a fresh read of the caps doc''' #int warning (QWidget parent, QString title, QString text, QString button0Text, QString button1Text = QString(), QString button2Text = QString(), int defaultButtonNumber = 0, int escapeButtonNumber = -1) ans = QMessageBox.warning(self, "Reset","This action will overwrite your Layer Configuration using the current LDS settings (potentially adding new or removing layers). Continue?","Continue","Cancel") if ans: #Cancel ldslog.warn('Cancelling Reset operation') return #Continue ldslog.warn('Reset Layer Config') self.parent.resetLayers() self.keywordcombo.clear() def checkKeyword(self,ktext): '''Checks keyword isn't null and isn't part of the LDS supplied keywords''' if LU.assessNone(ktext) is None: QMessageBox.about(self, "Keyword Required","Please enter a Keyword to assign Layer(s) to") return False if ktext in self.confconn_link.reserved: QMessageBox.about(self, "Reserved Keyword","'{}' is a reserved keyword, please select again".format(ktext)) return False return True
class acfPlot(genericPlot): def __init__(self, parent, sound, prm): genericPlot.__init__(self, parent, prm) self.prm = parent.prm self.currLocale = self.parent().prm['data']['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) self.sound = sound self.win = self.prm['pref']['smoothingWindow'] self.lineCol = pltColorFromQColor(self.prm['pref']['lineColor1']) self.lineWidth = self.prm['pref']['line_width'] self.xAxisLabel = self.prm['pref']['acf_x_axis_label'] self.yAxisLabel = self.prm['pref']['acf_y_axis_label'] self.firstRun = True self.getData() self.plotData() self.setAxesLabels() self.canvas.draw() self.setWindowTitle(self.sound['label'] + ' [' + self.sound['chan'] +']') def createAdditionalControlWidgets(self): self.windowChooser = QComboBox() self.windowChooser.addItems(self.prm['data']['available_windows']) self.windowChooser.setCurrentIndex(self.windowChooser.findText(self.prm['pref']['smoothingWindow'])) self.windowChooserLabel = QLabel(self.tr('Window:')) self.gridBox.addWidget(self.windowChooserLabel, 0, 4) self.gridBox.addWidget(self.windowChooser, 0, 5) self.windowChooser.currentIndexChanged[int].connect(self.onChangeWindowFunction) def getData(self): maxLag = self.sound['nSamples']/float(self.sound['fs']) (lags, acf) = getAcf(self.sound['wave'], self.sound['fs'], maxLag, True, self.win) self.sound['lagArr'] = lags self.sound['acf'] = acf self.sound['maxLag'] = maxLag def plotData(self): self.line, = self.axes.plot(self.sound['lagArr'], self.sound['acf'], color=self.lineCol) if self.firstRun == True: self.xminWidget.setText(self.currLocale.toString(self.axes.get_xlim()[0])) self.xmaxWidget.setText(self.currLocale.toString(self.axes.get_xlim()[1])) self.yminWidget.setText(self.currLocale.toString(self.axes.get_ylim()[0])) self.ymaxWidget.setText(self.currLocale.toString(self.axes.get_ylim()[1])) self.firstRun = False def setAxesLabels(self): self.axes.set_xlabel(self.tr('Lag (s)')) self.axes.set_ylabel(self.tr('Correlation')) def onChangeWindowFunction(self): self.win = self.windowChooser.currentText() self.updatePlot() def updatePlot(self): self.axes.clear() self.getData() self.plotData() self.onAxesChange() self.setAxesLabels() self.toggleGrid(None) self.canvas.draw() def createAdditionalMenus(self): self.editLineWidthAction = QAction(self.tr('Line Width'), self) self.editLineWidthAction.triggered.connect(self.onChangeLineWidth) self.editLineColorAction = QAction(self.tr('Line Color'), self) self.editLineColorAction.triggered.connect(self.onChangeLineColor) def defineMenusLayout(self): self.linePropertiesMenu.addAction(self.editLineWidthAction) self.linePropertiesMenu.addAction(self.editMajorTickLengthAction) self.linePropertiesMenu.addAction(self.editMajorTickWidthAction) self.linePropertiesMenu.addAction(self.editMinorTickLengthAction) self.linePropertiesMenu.addAction(self.editMinorTickWidthAction) self.linePropertiesMenu.addAction(self.editGridLineWidthAction) self.linePropertiesMenu.addAction(self.editSpinesLineWidthAction) self.colorPropertiesMenu.addAction(self.editLineColorAction) self.colorPropertiesMenu.addAction(self.editBackgroundColorAction) self.colorPropertiesMenu.addAction(self.editCanvasColorAction) self.colorPropertiesMenu.addAction(self.editAxesColorAction) self.colorPropertiesMenu.addAction(self.editGridColorAction) self.colorPropertiesMenu.addAction(self.editTickLabelColorAction) self.colorPropertiesMenu.addAction(self.editAxesLabelColorAction) self.labelPropertiesMenu.addAction(self.editXLabelAction) self.labelPropertiesMenu.addAction(self.editYLabelAction) self.labelPropertiesMenu.addAction(self.editLabelFontAction) self.labelPropertiesMenu.addAction(self.editTickLabelFontAction) def onChangeLineColor(self): col = QColorDialog.getColor() if col.isValid(): self.lineCol = pltColorFromQColor(col) self.line.set_color(self.lineCol) self.canvas.draw() def onChangeLineWidth(self): msg = self.tr('Line Width:') value, ok = QInputDialog.getDouble(self, self.tr('Input Dialog'), msg, self.lineWidth, 0) if ok: self.lineWidth = value self.line.set_linewidth(self.lineWidth) self.canvas.draw()
class SimulationPanel(QWidget): def __init__(self): QWidget.__init__(self) layout = QVBoxLayout() self._simulation_mode_combo = QComboBox() addHelpToWidget(self._simulation_mode_combo, "run/simulation_mode") self._simulation_mode_combo.currentIndexChanged.connect(self.toggleSimulationMode) simulation_mode_layout = QHBoxLayout() simulation_mode_layout.addSpacing(10) simulation_mode_layout.addWidget(QLabel("Simulation mode:"), 0, Qt.AlignVCenter) simulation_mode_layout.addWidget(self._simulation_mode_combo, 0, Qt.AlignVCenter) simulation_mode_layout.addSpacing(20) self.run_button = QToolButton() self.run_button.setIconSize(QSize(32, 32)) self.run_button.setText("Start Simulation") self.run_button.setIcon(resourceIcon("ide/gear_in_play")) self.run_button.clicked.connect(self.runSimulation) self.run_button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) addHelpToWidget(self.run_button, "run/start_simulation") simulation_mode_layout.addWidget(self.run_button) simulation_mode_layout.addStretch(1) layout.addSpacing(5) layout.addLayout(simulation_mode_layout) layout.addSpacing(10) self._simulation_stack = QStackedWidget() self._simulation_stack.setLineWidth(1) self._simulation_stack.setFrameStyle(QFrame.StyledPanel) layout.addWidget(self._simulation_stack) self._simulation_widgets = OrderedDict() """ :type: OrderedDict[BaseRunModel,SimulationConfigPanel]""" self.addSimulationConfigPanel(EnsembleExperimentPanel()) self.addSimulationConfigPanel(EnsembleSmootherPanel()) self.addSimulationConfigPanel(IteratedEnsembleSmootherPanel(advanced_option=True)) self.addSimulationConfigPanel(MultipleDataAssimilationPanel()) self.setLayout(layout) def addSimulationConfigPanel(self, panel): assert isinstance(panel, SimulationConfigPanel) panel.toggleAdvancedOptions(False) self._simulation_stack.addWidget(panel) simulation_model = panel.getSimulationModel() self._simulation_widgets[simulation_model] = panel if not panel.is_advanced_option: self._simulation_mode_combo.addItem(str(simulation_model), simulation_model) panel.simulationConfigurationChanged.connect(self.validationStatusChanged) def getActions(self): return [] def toggleAdvancedOptions(self, show_advanced): current_model = self.getCurrentSimulationModel() self._simulation_mode_combo.clear() for model, panel in self._simulation_widgets.iteritems(): if show_advanced or not panel.is_advanced_option: self._simulation_mode_combo.addItem(str(model), model) old_index = self._simulation_mode_combo.findText(str(current_model)) self._simulation_mode_combo.setCurrentIndex(old_index if old_index > -1 else 0) def toggleAdvancedMode(self, show_advanced): for panel in self._simulation_widgets.values(): panel.toggleAdvancedOptions(show_advanced) self.toggleAdvancedOptions(show_advanced) def getCurrentSimulationModel(self): data = self._simulation_mode_combo.itemData(self._simulation_mode_combo.currentIndex(), Qt.UserRole) return data.toPyObject() def getSimulationArguments(self): """ @rtype: dict[str,object]""" simulation_widget = self._simulation_widgets[self.getCurrentSimulationModel()] return simulation_widget.getSimulationArguments() def runSimulation(self): case_name = getCurrentCaseName() message = "Are you sure you want to use case '%s' for initialization of the initial ensemble when running the simulations?" % case_name start_simulations = QMessageBox.question(self, "Start simulations?", message, QMessageBox.Yes | QMessageBox.No ) if start_simulations == QMessageBox.Yes: run_model = self.getCurrentSimulationModel() arguments = self.getSimulationArguments() dialog = RunDialog(run_model, arguments, self) dialog.startSimulation() dialog.exec_() ERT.emitErtChange() # simulations may have added new cases. def toggleSimulationMode(self): current_model = self.getCurrentSimulationModel() if current_model is not None: widget = self._simulation_widgets[self.getCurrentSimulationModel()] self._simulation_stack.setCurrentWidget(widget) self.validationStatusChanged() def validationStatusChanged(self): widget = self._simulation_widgets[self.getCurrentSimulationModel()] self.run_button.setEnabled(widget.isConfigurationValid())
class ShowSettingsDialog(QDialog): """ Dialog class for plugin settings """ def __init__(self, iface, memoryPointsLayer, memoryLinesLayer, ctllDb, configTable, uriDb, schemaDb, mntUrl, refLayers, adjLayers, levelAtt, levelVal, drawdowmLayer, pipeDiam, moreTools): """ Constructor :param iface: interface :param memoryPointsLayer: working memory points layer :param memoryLinesLayer: working memory lines layer :param configTable: config table selected for import """ QDialog.__init__(self) self.__iface = iface self.__memoryPointsLayer = memoryPointsLayer self.__memoryLinesLayer = memoryLinesLayer self.__ctlDb = ctllDb self.__configTable = configTable self.__uriDb = uriDb self.__schemaDb = schemaDb self.__mntUrl = mntUrl self.__refLayers = refLayers self.__adjLayers = adjLayers self.__levelAtt = levelAtt self.__levelVal = levelVal self.__drawdowmLayer = drawdowmLayer self.__pipeDiam = pipeDiam self.setWindowTitle(QCoreApplication.translate("VDLTools", "Settings")) self.__pointsLayers = [] self.__linesLayers = [] self.__refAvailableLayers = [] self.__drawdownLayers = [] self.__tables = [] self.__schemas = [] self.__pipeDiamFields = [] self.__levelAttFields = [] self.__dbs = DBConnector.getUsedDatabases() self.__refLabels = [] self.__refChecks = [] self.__adjChecks = [] for layer in list(QgsMapLayerRegistry.instance().mapLayers().values()): if layer is not None and layer.type() == QgsMapLayer.VectorLayer: if layer.providerType() == "memory": if layer.geometryType() == QGis.Point: self.__pointsLayers.append(layer) if layer.geometryType() == QGis.Line: self.__linesLayers.append(layer) if QGis.fromOldWkbType(layer.wkbType()) == QgsWKBTypes.LineStringZ: self.__drawdownLayers.append(layer) if QGis.fromOldWkbType(layer.wkbType()) == QgsWKBTypes.PointZ: self.__refAvailableLayers.append(layer) # self.resize(450, 400) self.__layout = QGridLayout() line = 0 intersectLabel = QLabel(QCoreApplication.translate("VDLTools", "Intersect ")) self.__layout.addWidget(intersectLabel, line, 0) line += 1 pointLabel = QLabel(QCoreApplication.translate("VDLTools", "Working points layer : ")) self.__layout.addWidget(pointLabel, line, 1) self.__pointCombo = QComboBox() self.__pointCombo.setMinimumHeight(20) self.__pointCombo.setMinimumWidth(50) self.__pointCombo.addItem("") for layer in self.__pointsLayers: self.__pointCombo.addItem(layer.name()) self.__layout.addWidget(self.__pointCombo, line, 2) self.__pointCombo.currentIndexChanged.connect(self.__pointComboChanged) if self.__memoryPointsLayer is not None: if self.__memoryPointsLayer in self.__pointsLayers: self.__pointCombo.setCurrentIndex(self.__pointsLayers.index(self.__memoryPointsLayer)+1) line += 1 lineLabel = QLabel(QCoreApplication.translate("VDLTools", "Working lines layer : ")) self.__layout.addWidget(lineLabel, line, 1) self.__lineCombo = QComboBox() self.__lineCombo.setMinimumHeight(20) self.__lineCombo.setMinimumWidth(50) self.__lineCombo.addItem("") for layer in self.__linesLayers: self.__lineCombo.addItem(layer.name()) self.__layout.addWidget(self.__lineCombo, line, 2) self.__lineCombo.currentIndexChanged.connect(self.__lineComboChanged) if self.__memoryLinesLayer is not None: if self.__memoryLinesLayer in self.__linesLayers: self.__lineCombo.setCurrentIndex(self.__linesLayers.index(self.__memoryLinesLayer)+1) line += 1 profilesLabel = QLabel(QCoreApplication.translate("VDLTools", "Profiles ")) self.__layout.addWidget(profilesLabel, line, 0) line += 1 mntLabel = QLabel(QCoreApplication.translate("VDLTools", "Url for MNT : ")) self.__layout.addWidget(mntLabel, line, 1) self.__mntText = QLineEdit() if self.__mntUrl is None or self.__mntUrl == "None": self.__mntText.insert('https://map.lausanne.ch/prod/wsgi/profile.json') else: self.__mntText.insert(self.__mntUrl) self.__mntText.setMinimumHeight(20) self.__mntText.setMinimumWidth(100) self.__layout.addWidget(self.__mntText, line, 2) line += 1 ddLabel = QLabel(QCoreApplication.translate("VDLTools", "Drawdown ")) self.__layout.addWidget(ddLabel, line, 0) line += 1 self.__layout.addWidget(QLabel(QCoreApplication.translate("VDLTools", "Layer")), line, 1) namesLayout = QHBoxLayout() namesWidget = QWidget() namesLayout.addWidget(QLabel(QCoreApplication.translate("VDLTools", "Reference"))) namesLayout.addWidget(QLabel(QCoreApplication.translate("VDLTools", "Adjustable"))) namesLayout.setContentsMargins(0,0,0,0) namesWidget.setLayout(namesLayout) self.__layout.addWidget(namesWidget, line, 2) line += 1 for layer in self.__refAvailableLayers: refLabel = QLabel(" - " + layer.name()) self.__refLabels.append(refLabel) self.__layout.addWidget(refLabel, line, 1) checksLayout = QHBoxLayout() checksLayout.setContentsMargins(0,0,0,0) checksWidget = QWidget() refCheck = QCheckBox() self.__refChecks.append(refCheck) refCheck.stateChanged.connect(self.__refBoxesChanged) checksLayout.addWidget(refCheck) adjCheck = QCheckBox() self.__adjChecks.append(adjCheck) checksLayout.addWidget(adjCheck) checksWidget.setLayout(checksLayout) self.__layout.addWidget(checksWidget, line, 2) line += 1 levelAttLabel = QLabel(QCoreApplication.translate("VDLTools", "Code(s) on pipe : ")) self.__layout.addWidget(levelAttLabel, line, 1) self.__levelAttCombo = QComboBox() self.__levelAttCombo.setMinimumHeight(20) self.__levelAttCombo.setMinimumWidth(50) self.__levelAttCombo.addItem("") self.__layout.addWidget(self.__levelAttCombo, line, 2) self.__levelAttCombo.currentIndexChanged.connect(self.__levelAttComboChanged) i = 0 for layer in self.__refAvailableLayers: if layer in self.__refLayers: self.__refChecks[i].setChecked(True) if layer in self.__adjLayers: self.__adjChecks[i].setChecked(True) i += 1 line += 1 levelValLabel = QLabel(QCoreApplication.translate("VDLTools", "Point code attribute : ")) self.__layout.addWidget(levelValLabel, line, 1) self.__levelValText = QLineEdit() if self.__levelVal is not None and self.__levelVal != "None": self.__levelValText.insert(self.__levelVal) self.__levelValText.setMinimumHeight(20) self.__levelValText.setMinimumWidth(100) self.__layout.addWidget(self.__levelValText, line, 2) line += 1 drawdownLabel = QLabel(QCoreApplication.translate("VDLTools", "drawdown layer : ")) self.__layout.addWidget(drawdownLabel, line, 1) self.__drawdownCombo = QComboBox() self.__drawdownCombo.setMinimumHeight(20) self.__drawdownCombo.setMinimumWidth(50) self.__drawdownCombo.addItem("") for layer in self.__drawdownLayers: self.__drawdownCombo.addItem(layer.name()) self.__layout.addWidget(self.__drawdownCombo, line, 2) line += 1 pipeDiamLabel = QLabel(QCoreApplication.translate("VDLTools", "Pipe diameter attribute [cm] : ")) self.__layout.addWidget(pipeDiamLabel, line, 1) self.__pipeDiamCombo = QComboBox() self.__pipeDiamCombo.setMinimumHeight(20) self.__pipeDiamCombo.setMinimumWidth(50) self.__pipeDiamCombo.addItem("") self.__layout.addWidget(self.__pipeDiamCombo, line, 2) self.__drawdownCombo.currentIndexChanged.connect(self.__drawdownComboChanged) self.__pipeDiamCombo.currentIndexChanged.connect(self.__pipeDiamComboChanged) if self.__drawdowmLayer is not None: if self.__drawdowmLayer in self.__drawdownLayers: self.__drawdownCombo.setCurrentIndex(self.__drawdownLayers.index(self.__drawdowmLayer)+1) if moreTools: line += 1 importLabel = QLabel(QCoreApplication.translate("VDLTools", "Import ")) self.__layout.addWidget(importLabel, line, 0) line += 1 dbLabel = QLabel(QCoreApplication.translate("VDLTools", "Import database : ")) self.__layout.addWidget(dbLabel, line, 1) self.__dbCombo = QComboBox() self.__dbCombo.setMinimumHeight(20) self.__dbCombo.setMinimumWidth(50) self.__dbCombo.addItem("") for db in list(self.__dbs.keys()): self.__dbCombo.addItem(db) self.__layout.addWidget(self.__dbCombo, line, 2) line += 1 schemaLabel = QLabel(QCoreApplication.translate("VDLTools", "Database schema : ")) self.__layout.addWidget(schemaLabel, line, 1) self.__schemaCombo = QComboBox() self.__schemaCombo.setMinimumHeight(20) self.__schemaCombo.setMinimumWidth(50) self.__schemaCombo.addItem("") self.__layout.addWidget(self.__schemaCombo, line, 2) line += 1 tableLabel = QLabel(QCoreApplication.translate("VDLTools", "Config table : ")) self.__layout.addWidget(tableLabel, line, 1) self.__tableCombo = QComboBox() self.__tableCombo.setMinimumHeight(20) self.__tableCombo.setMinimumWidth(50) self.__tableCombo.addItem("") self.__layout.addWidget(self.__tableCombo, line, 2) line += 1 controlLabel = QLabel(QCoreApplication.translate("VDLTools", "Control ")) self.__layout.addWidget(controlLabel, line, 0) line += 1 ctlLabel = QLabel(QCoreApplication.translate("VDLTools", "Control database : ")) self.__layout.addWidget(ctlLabel, line, 1) self.__ctlCombo = QComboBox() self.__ctlCombo.setMinimumHeight(20) self.__ctlCombo.setMinimumWidth(50) self.__ctlCombo.addItem("") for db in list(self.__dbs.keys()): self.__ctlCombo.addItem(db) self.__layout.addWidget(self.__ctlCombo, line, 2) self.__dbCombo.currentIndexChanged.connect(self.__dbComboChanged) self.__schemaCombo.currentIndexChanged.connect(self.__schemaComboChanged) self.__tableCombo.currentIndexChanged.connect(self.__tableComboChanged) self.__ctlCombo.currentIndexChanged.connect(self.__ctlComboChanged) if self.__uriDb is not None: if self.__uriDb.database() in list(self.__dbs.keys()): self.__dbCombo.setCurrentIndex(list(self.__dbs.keys()).index(self.__uriDb.database()) + 1) if self.__ctlDb is not None: if self.__ctlDb.database() in list(self.__dbs.keys()): self.__ctlCombo.setCurrentIndex(list(self.__dbs.keys()).index(self.__ctlDb.database()) + 1) else: self.__dbCombo = None self.__schemaCombo = None self.__tableCombo = None self.__ctlCombo = None self.__okButton = QPushButton(QCoreApplication.translate("VDLTools", "OK")) self.__okButton.setMinimumHeight(20) self.__okButton.setMinimumWidth(100) self.__cancelButton = QPushButton(QCoreApplication.translate("VDLTools", "Cancel")) self.__cancelButton.setMinimumHeight(20) self.__cancelButton.setMinimumWidth(100) self.__layout.addWidget(self.__okButton, 100, 1) self.__layout.addWidget(self.__cancelButton, 100, 2) self.setLayout(self.__layout) @staticmethod def __resetCombo(combo): """ To reset a combo list :param combo: concerned combo """ while combo.count() > 0: combo.removeItem(combo.count()-1) def __setSchemaCombo(self, uriDb): """ To fill the schema combo list :param uriDb: selected database uri """ connector = DBConnector(uriDb, self.__iface) db = connector.setConnection() if db: Signal.safelyDisconnect(self.__schemaCombo.currentIndexChanged, self.__schemaComboChanged) self.__resetCombo(self.__schemaCombo) self.__schemaCombo.addItem("") self.__schemas = [] query = db.exec_("""SELECT DISTINCT table_schema FROM information_schema.tables WHERE table_schema NOT IN ('pg_catalog', 'information_schema', 'topology') AND table_type = 'BASE TABLE' AND table_name NOT IN (SELECT f_table_name FROM geometry_columns)""") if query.lastError().isValid(): self.__iface.messageBar().pushMessage(query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: while next(query): self.__schemas.append(query.value(0)) db.close() for schema in self.__schemas: self.__schemaCombo.addItem(schema) self.__schemaCombo.currentIndexChanged.connect(self.__schemaComboChanged) if self.__schemaDb is not None: if self.__schemaDb in self.__schemas: self.__schemaCombo.setCurrentIndex(self.__schemas.index(self.__schemaDb) + 1) def __setTableCombo(self, uriDb, schema): """ To fill the table combo list :param uriDb: selected database uri :param schema: selected database schema """ connector = DBConnector(uriDb, self.__iface) db = connector.setConnection() if db: Signal.safelyDisconnect(self.__tableCombo.currentIndexChanged, self.__tableComboChanged) self.__resetCombo(self.__tableCombo) self.__tableCombo.addItem("") self.__tables = [] query = db.exec_("""SELECT table_name FROM information_schema.tables WHERE table_schema = '""" + schema + """' ORDER BY table_name""") if query.lastError().isValid(): self.__iface.messageBar().pushMessage(query.lastError().text(), level=QgsMessageBar.CRITICAL, duration=0) else: while next(query): self.__tables.append(query.value(0)) db.close() for table in self.__tables: if self.__tableCombo.findText(table) == -1: self.__tableCombo.addItem(table) self.__tableCombo.currentIndexChanged.connect(self.__tableComboChanged) if self.__configTable is not None: if self.__configTable in self.__tables: self.__tableCombo.setCurrentIndex(self.__tables.index(self.__configTable) + 1) def __setPipeDiamCombo(self, drawdownLayer): """ To fill the pipe diameter combo list :param drawdownLayer: choosen drawdown layer """ Signal.safelyDisconnect(self.__pipeDiamCombo.currentIndexChanged, self.__pipeDiamComboChanged) self.__resetCombo(self.__pipeDiamCombo) self.__pipeDiamCombo.addItem("") fields = drawdownLayer.fields() self.__pipeDiamFields = [] for field in fields: self.__pipeDiamFields.append(field.name()) self.__pipeDiamCombo.addItem(field.name()) self.__pipeDiamCombo.currentIndexChanged.connect(self.__pipeDiamComboChanged) if self.__pipeDiam is not None: if self.__pipeDiam in self.__pipeDiamFields: self.__pipeDiamCombo.setCurrentIndex(self.__pipeDiamFields.index(self.__pipeDiam) + 1) def __setLevelAttCombo(self, refLayers): """ To fill the level attribute combo list :param refLayers: choosen reference layers """ Signal.safelyDisconnect(self.__levelAttCombo.currentIndexChanged, self.__levelAttComboChanged) self.__resetCombo(self.__levelAttCombo) self.__levelAttCombo.addItem("") self.__levelAttFields = [] num = 0 for layer in refLayers: fields = layer.fields() if num == 0: for field in fields: self.__levelAttFields.append(field.name()) num = 1 else: names = [] for field in fields: names.append(field.name()) news = [] for name in self.__levelAttFields: if name in names: news.append(name) self.__levelAttFields = news for name in self.__levelAttFields: self.__levelAttCombo.addItem(name) self.__levelAttCombo.currentIndexChanged.connect(self.__levelAttComboChanged) if self.__levelAtt is not None: if self.__levelAtt in self.__levelAttFields: self.__levelAttCombo.setCurrentIndex(self.__levelAttFields.index(self.__levelAtt) + 1) def __lineComboChanged(self): """ To remove blank item when another one is selected """ if self.__lineCombo.itemText(0) == "": self.__lineCombo.removeItem(0) def __pointComboChanged(self): """ To remove blank item when another one is selected """ if self.__pointCombo.itemText(0) == "": self.__pointCombo.removeItem(0) def __refBoxesChanged(self): """ To update level attribute combo when reference layers have changed """ if self.refLayers() is not None: self.__setLevelAttCombo(self.refLayers()) def __drawdownComboChanged(self): """ To remove blank item when another one is selected and update pipe diamete combo when drawdown layer has changed """ if self.__drawdownCombo.itemText(0) == "": self.__drawdownCombo.removeItem(0) if self.drawdownLayer() is not None: self.__setPipeDiamCombo(self.drawdownLayer()) def __tableComboChanged(self): """ To remove blank item when another one is selected """ if self.__tableCombo.itemText(0) == "": self.__tableCombo.removeItem(0) def __dbComboChanged(self): """ When the selection in db combo has changed """ if self.__dbCombo.itemText(0) == "": self.__dbCombo.removeItem(0) if self.uriDb() is not None: self.__setSchemaCombo(self.uriDb()) def __schemaComboChanged(self): """ When the selection in schema combo has changed """ if self.__schemaCombo.itemText(0) == "": self.__schemaCombo.removeItem(0) if self.schemaDb() is not None: self.__setTableCombo(self.uriDb(), self.schemaDb()) def __pipeDiamComboChanged(self): """ When the selection in schema combo has changed """ if self.__pipeDiamCombo.itemText(0) == "": self.__pipeDiamCombo.removeItem(0) def __levelAttComboChanged(self): """ When the selection in schema combo has changed """ if self.__levelAttCombo.itemText(0) == "": self.__levelAttCombo.removeItem(0) def __ctlComboChanged(self): """ When the selection in ctl combo has changed """ if self.__ctlCombo.itemText(0) == "": self.__ctlCombo.removeItem(0) def okButton(self): """ To get the ok button instance :return: ok button instance """ return self.__okButton def cancelButton(self): """ To get the cancel button instance :return: cancel button instance """ return self.__cancelButton def pointsLayer(self): """ To get the selected memory points layer :return: selected memory points layer, or none """ index = self.__pointCombo.currentIndex() if self.__pointCombo.itemText(index) == "": return None else: return self.__pointsLayers[index] def linesLayer(self): """ To get the selected memory lines layer :return: selected memory lines layer, or none """ index = self.__lineCombo.currentIndex() if self.__lineCombo.itemText(index) == "": return None else: return self.__linesLayers[index] def refLayers(self): """ To get the selected reference layers :return: selected reference layers, or none """ layers = [] i = 0 for check in self.__refChecks: if check.isChecked(): layers.append(self.__refAvailableLayers[i]) i += 1 return layers def adjLayers(self): """ To get the selected ajustable layers :return: selected adjustable layers, or none """ layers = [] i = 0 for check in self.__adjChecks: if check.isChecked(): layers.append(self.__refAvailableLayers[i]) i += 1 return layers def levelAtt(self): """ To get the selected level attribute :return: selected level attribute, or none """ if self.__levelAttCombo is None: return None index = self.__levelAttCombo.currentIndex() if self.__levelAttCombo.itemText(index) == "": return None else: return self.__levelAttFields[index] def levelVal(self): """ To get the filled level value :return: filled level value """ return self.__levelValText.text() def drawdownLayer(self): """ To get the selected drawdown layer :return: selected drawdown layer, or none """ index = self.__drawdownCombo.currentIndex() if self.__drawdownCombo.itemText(index) == "": return None else: return self.__drawdownLayers[index] def pipeDiam(self): """ To get the selected pipe diameter :return: selected pipe diameter, or none """ if self.__pipeDiamCombo is None: return None index = self.__pipeDiamCombo.currentIndex() if self.__pipeDiamCombo.itemText(index) == "": return None else: return self.__pipeDiamFields[index] def configTable(self): """ To get the selected config table :return: selected config table, or none """ if self.__tableCombo is None: return None index = self.__tableCombo.currentIndex() if self.__tableCombo.itemText(index) == "": return None else: return self.__tables[index] def uriDb(self): """ To get selected import database uri :return: import database uri """ if self.__dbCombo is None: return None index = self.__dbCombo.currentIndex() if self.__dbCombo.itemText(index) == "": return None else: return self.__dbs[list(self.__dbs.keys())[index]] def schemaDb(self): """ To get selected import database schema :return: import database schema """ if self.__schemaCombo is None: return None index = self.__schemaCombo.currentIndex() if self.__schemaCombo.itemText(index) == "": return None else: return self.__schemas[index] def mntUrl(self): """ To get selected MN url :return: MN url """ return self.__mntText.text() def ctlDb(self): """ To get selected control database uri :return: control database uri """ if self.__ctlCombo is None: return None index = self.__ctlCombo.currentIndex() if self.__ctlCombo.itemText(index) == "": return None else: return self.__dbs[list(self.__dbs.keys())[index]]
class XTimeDeltaEdit(QFrame): def __init__(self, parent=None): super(XTimeDeltaEdit, self).__init__(parent) # define custom properties self.setStyleSheet(COMBO_STYLE) self._numberSpinner = QSpinBox(self) self._numberSpinner.setRange(0, 100000) self._numberSpinner.setFrame(False) self._numberSpinner.setButtonSymbols(QSpinBox.NoButtons) self._numberSpinner.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self._unitCombo = QComboBox(self) self._unitCombo.setEditable(True) self._unitCombo.setInsertPolicy(QComboBox.NoInsert) self._unitCombo.setFrame(False) self._unitCombo.addItems(['year(s)', 'month(s)', 'week(s)', 'day(s)', 'hour(s)', 'minute(s)', 'second(s)']) self._unitCombo.setCurrentIndex(3) self._unitCombo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self._directionCombo = QComboBox(self) self._directionCombo.addItems(['ago', 'from now']) self._directionCombo.setEditable(True) self._directionCombo.setInsertPolicy(QComboBox.NoInsert) self._directionCombo.setFrame(False) self._directionCombo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # setup ui self.setFrameShape(QFrame.StyledPanel) self.setFrameShadow(QFrame.Sunken) self.setBackgroundRole(QPalette.Base) self.setAutoFillBackground(True) layout = QHBoxLayout() layout.setContentsMargins(2, 2, 2, 2) layout.setSpacing(0) layout.addWidget(self._numberSpinner) layout.addWidget(self._unitCombo) layout.addWidget(self._directionCombo) self.setLayout(layout) def delta(self): """ Returns a delta based on this widget's information. :return <datetime.timedelta> """ number = self._numberSpinner.value() unit = self._unitCombo.currentText() direction = self._directionCombo.currentText() # use past tense if direction == 'ago': number = -number if unit == 'year(s)': return datetime.timedelta(number * 365) elif unit == 'month(s)': return datetime.timedelta(number * 30) elif unit == 'week(s)': return datetime.timedelta(number * 7) elif unit == 'day(s)': return datetime.timedelta(number) elif unit == 'hour(s)': return datetime.timedelta(0, number * 3600) elif unit == 'minute(s)': return datetime.timedelta(0, number * 60) else: return datetime.timedelta(0, number) def setDelta(self, delta): """ Sets the time delta for this widget to the inputed delta. :param delta | <datetime.timedelta> """ days = int(delta.days) secs = int(delta.total_seconds()) direction = 'from now' if secs < 0: direction = 'ago' if days and days % 365 == 0: number = days / 365 unit = 'year(s)' elif days and days % 30 == 0: number = days / 30 unit = 'month(s)' elif days and days % 7 == 0: number = days / 7 unit = 'week(s)' elif days: number = days unit = 'day(s)' elif secs % 3600 == 0: number = secs / 3600 unit = 'hour(s)' elif secs % 60 == 0: number = secs / 60 unit = 'minute(s)' else: number = secs unit = 'second(s)' self._numberSpinner.setValue(abs(int(number))) self._unitCombo.setCurrentIndex(self._unitCombo.findText(unit)) index = self._directionCombo.findText(direction) self._directionCombo.setCurrentIndex(index)
class preferencesDialog(QDialog): def __init__(self, parent): QDialog.__init__(self, parent) self.tmpPref = {} self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref']) self.currLocale = self.parent().prm['data']['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) self.tabWidget = QTabWidget() self.tabWidget.currentChanged.connect(self.tabChanged) self.appPrefWidget = QWidget() self.plotPrefWidget = QWidget() self.signalPrefWidget = QWidget() self.soundPrefWidget = QWidget() #APP PREF appPrefGrid = QGridLayout() n = 0 self.languageChooserLabel = QLabel(self.tr('Language (requires restart):')) appPrefGrid.addWidget(self.languageChooserLabel, n, 0) self.languageChooser = QComboBox() self.languageChooser.addItems(self.parent().prm['data']['available_languages']) self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language'])) self.languageChooser.currentIndexChanged[int].connect(self.onLanguageChooserChange) appPrefGrid.addWidget(self.languageChooser, n, 1) n = n+1 self.countryChooserLabel = QLabel(self.tr('Country (requires restart):')) appPrefGrid.addWidget(self.countryChooserLabel, n, 0) self.countryChooser = QComboBox() self.countryChooser.addItems(self.parent().prm['data']['available_countries'][self.tmpPref['pref']['language']]) self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country'])) appPrefGrid.addWidget(self.countryChooser, n, 1) self.appPrefWidget.setLayout(appPrefGrid) #PLOT PREF plotPrefGrid = QGridLayout() n = 0 #LINE COLOUR self.lineColor1 = self.tmpPref['pref']['lineColor1'] self.lineColorButton = QPushButton(self.tr("Line Color"), self) self.lineColorButton.clicked.connect(self.onChangeLineColor) plotPrefGrid.addWidget(self.lineColorButton, n, 0) self.lineColorSquare = QWidget(self) self.lineColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.lineColor1.name()) plotPrefGrid.addWidget(self.lineColorSquare, n, 1) n = n+1 self.backgroundColor = self.tmpPref['pref']['backgroundColor'] self.backgroundColorButton = QPushButton(self.tr("Background Color"), self) self.backgroundColorButton.clicked.connect(self.onChangeBackgroundColor) plotPrefGrid.addWidget(self.backgroundColorButton, n, 0) self.backgroundColorSquare = QWidget(self) self.backgroundColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.backgroundColor.name()) plotPrefGrid.addWidget(self.backgroundColorSquare, n, 1) n = n+1 self.canvasColor = self.tmpPref['pref']['canvasColor'] self.canvasColorButton = QPushButton(self.tr("Canvas Color"), self) self.canvasColorButton.clicked.connect(self.onChangeCanvasColor) plotPrefGrid.addWidget(self.canvasColorButton, n, 0) self.canvasColorSquare = QWidget(self) self.canvasColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.canvasColor.name()) plotPrefGrid.addWidget(self.canvasColorSquare, n, 1) n = n+1 self.dpiLabel = QLabel(self.tr('DPI - Resolution:')) plotPrefGrid.addWidget(self.dpiLabel, n, 0) self.dpiWidget = QLineEdit(str(self.tmpPref['pref']['dpi'])) plotPrefGrid.addWidget(self.dpiWidget, n, 1) self.dpiWidget.setValidator(QIntValidator(self)) self.dpiWidget.editingFinished.connect(self.ondpiChange) n = n+1 self.cmapChooserLabel = QLabel(self.tr('Color Map:')) plotPrefGrid.addWidget(self.cmapChooserLabel, n, 0) self.cmapChooser = QComboBox() self.cmapChooser.addItems(self.parent().prm['data']['available_colormaps']) self.cmapChooser.setCurrentIndex(self.cmapChooser.findText(self.tmpPref['pref']['colormap'])) plotPrefGrid.addWidget(self.cmapChooser, n, 1) n = n+1 self.gridOn = QCheckBox(self.tr('Grid')) self.gridOn.setChecked(self.tmpPref['pref']['grid']) plotPrefGrid.addWidget(self.gridOn, n, 1) self.plotPrefWidget.setLayout(plotPrefGrid) #SIGNAL PREF signalPrefGrid = QGridLayout() n = 0 self.windowChooser = QComboBox() self.windowChooser.addItems(self.parent().prm['data']['available_windows']) self.windowChooser.setCurrentIndex(self.windowChooser.findText(self.tmpPref['pref']['smoothingWindow'])) self.windowChooserLabel = QLabel(self.tr('Window:')) signalPrefGrid.addWidget(self.windowChooserLabel, 0, 0) signalPrefGrid.addWidget(self.windowChooser, 0, 1) n = n+1 self.signalPrefWidget.setLayout(signalPrefGrid) #SOUND PREF soundPrefGrid = QGridLayout() n = 0 self.wavmanagerLabel = QLabel(self.tr('Wav Manager (requires restart):')) self.wavmanagerChooser = QComboBox() self.wavmanagerChooser.addItems(["scipy"]) self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['wavmanager'])) soundPrefGrid.addWidget(self.wavmanagerLabel, n, 0) soundPrefGrid.addWidget(self.wavmanagerChooser, n, 1) n = n+1 self.playChooser = QComboBox() self.playChooser.addItems(self.parent().prm['data']['available_play_commands']) self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['playCommandType'])) self.playChooser.currentIndexChanged[int].connect(self.onPlayChooserChange) self.playChooserLabel = QLabel(self.tr('Play Command:')) soundPrefGrid.addWidget(self.playChooserLabel, n, 0) soundPrefGrid.addWidget(self.playChooser, n, 1) n = n+1 self.playCommandLabel = QLabel(self.tr('Command:')) soundPrefGrid.addWidget(self.playCommandLabel, n, 0) self.playCommandWidget = QLineEdit(str(self.tmpPref['pref']['playCommand'])) self.playCommandWidget.setReadOnly(True) soundPrefGrid.addWidget(self.playCommandWidget, n, 1) n = n+1 self.maxLevelLabel = QLabel(self.tr('Max Level:')) soundPrefGrid.addWidget(self.maxLevelLabel, n, 0) self.maxLevelWidget = QLineEdit(self.currLocale.toString(self.tmpPref['pref']['maxLevel'])) self.maxLevelWidget.setValidator(QDoubleValidator(self)) soundPrefGrid.addWidget(self.maxLevelWidget, n, 1) self.soundPrefWidget.setLayout(soundPrefGrid) self.tabWidget.addTab(self.appPrefWidget, self.tr("Applicatio&n")) self.tabWidget.addTab(self.plotPrefWidget, self.tr("Plot&s")) self.tabWidget.addTab(self.signalPrefWidget, self.tr("Signa&l")) self.tabWidget.addTab(self.soundPrefWidget, self.tr("Soun&d")) buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Ok|QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.permanentApply) layout = QVBoxLayout() layout.addWidget(self.tabWidget) layout.addWidget(buttonBox) self.setLayout(layout) def ondpiChange(self): try: val = int(self.dpiWidget.text()) except ValueError: QMessageBox.warning(self, self.tr('Warning'), self.tr('dpi value not valid')) self.dpiWidget.setText(str(self.tmpPref['pref']['dpi'])) val = int(self.dpiWidget.text()) if val < 10: QMessageBox.warning(self, self.tr('Warning'), self.tr('dpi value too small')) self.dpiWidget.setText(str(10)) def onChangeLineColor(self): col = QColorDialog.getColor() if col.isValid(): self.lineColor1 = col self.lineColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.lineColor1.name()) def onChangeCanvasColor(self): col = QColorDialog.getColor() if col.isValid(): self.canvasColor = col self.canvasColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.canvasColor.name()) def onChangeBackgroundColor(self): col = QColorDialog.getColor() if col.isValid(): self.backgroundColor = col self.backgroundColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.backgroundColor.name()) def onLanguageChooserChange(self): for i in range(self.countryChooser.count()): self.countryChooser.removeItem(0) self.countryChooser.addItems(self.parent().prm['data']['available_countries'][self.languageChooser.currentText()]) def onPlayChooserChange(self): foo = self.playChooser.currentText() if foo != self.tr('custom'): self.playCommandWidget.setText(foo) self.playCommandWidget.setReadOnly(True) else: self.playCommandWidget.setReadOnly(False) def tryApply(self): self.tmpPref['pref']['colormap'] = str(self.cmapChooser.currentText()) self.tmpPref['pref']['dpi'] = int(self.dpiWidget.text()) self.tmpPref['pref']['lineColor1'] = self.lineColor1 self.tmpPref['pref']['canvasColor'] = self.canvasColor self.tmpPref['pref']['backgroundColor'] = self.backgroundColor self.tmpPref['pref']['language'] = self.languageChooser.currentText() self.tmpPref['pref']['country'] = self.countryChooser.currentText() self.tmpPref['pref']['wavmanager'] = str(self.wavmanagerChooser.currentText()) self.tmpPref['pref']['playCommand'] = self.playCommandWidget.text() self.tmpPref['pref']['playCommandType'] = self.playChooser.currentText() self.tmpPref['pref']['maxLevel'] = self.currLocale.toDouble(self.maxLevelWidget.text())[0] if self.gridOn.isChecked(): self.tmpPref['pref']['grid'] = True else: self.tmpPref['pref']['grid'] = False self.tmpPref['pref']['smoothingWindow'] = str(self.windowChooser.currentText()) def revertChanges(self): self.cmapChooser.setCurrentIndex(self.cmapChooser.findText(self.tmpPref['pref']['colormap'])) self.dpiWidget.setText(str(self.tmpPref['pref']['dpi'])) self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language'])) self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country'])) self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['sound']['wavmanager'])) self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['playCommandType'])) self.playCommandWidget.setText(self.tmpPref['pref']['playCommand']) if self.playChooser.currentText() != self.tr('custom'): self.playCommandWidget.setReadOnly(True) self.maxLevelWidget.setText(str(self.tmpPref['pref']['maxLevel'])) self.gridOn.setChecked(self.tmpPref['pref']['grid']) self.windowChooser.setCurrentIndex(self.windowChooser.findText(self.tmpPref['pref']['smoothingWindow'])) self.lineColor1 = self.tmpPref['pref']['lineColor1'] self.lineColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.lineColor1.name()) self.canvasColor = self.tmpPref['pref']['canvasColor'] self.backgroundColor = self.tmpPref['pref']['backgroundColor'] self.backgroundColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.backgroundColor.name()) self.canvasColorSquare.setStyleSheet("QWidget { background-color: %s }" % self.canvasColor.name()) def permanentApply(self): self.tryApply() self.parent().prm['pref'] = copy.deepcopy(self.tmpPref['pref']) f = open(self.parent().prm['prefFile'], 'wb') pickle.dump(self.parent().prm['pref'], f) f.close() def tabChanged(self): self.tryApply() if self.tmpPref['pref'] != self.parent().prm['pref']: conf = applyChanges(self) if conf.exec_(): self.permanentApply() else: self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref']) self.revertChanges()
class SVDViewPanel(QWidget): svdSelectEvent = QtCore.pyqtSignal() axis_re = re.compile(r"^Axis (\d+)$") def __init__(self): QWidget.__init__(self) self.layout = QGridLayout(self) self.viewer = None self.x_label = QLabel("X axis:") self.x_chooser = QComboBox() self.x_chooser.setEditable(True) self.y_label = QLabel("Y axis:") self.y_chooser = QComboBox() self.y_chooser.setEditable(True) # TODO: add completers self.nav_reset = QPushButton("&Reset view") self.layout.addWidget(self.x_label, 1, 0) self.layout.addWidget(self.x_chooser, 1, 1) self.layout.addWidget(self.y_label, 1, 3) self.layout.addWidget(self.y_chooser, 1, 4) self.layout.addWidget(self.nav_reset, 1, 6) self.layout.setColumnStretch(1, 1) self.layout.setColumnStretch(4, 1) self.layout.setRowStretch(0, 1) self.nav_reset.clicked.connect(self.reset_view) self.x_chooser.currentIndexChanged['QString'].connect(self.set_x_from_string) self.y_chooser.currentIndexChanged['QString'].connect(self.set_y_from_string) self.x_chooser.activated['QString'].connect(self.set_x_from_string) def activate(self, docs, projections, magnitudes, canonical): self.deactivate() self.viewer = SVDViewer.make_svdview(docs, projections, magnitudes, canonical) self.layout.addWidget(self.viewer, 0, 0, 1, 7) self.setup_choosers(canonical) self.viewer.projection.rotated.connect(self.update_choosers) self.viewer.svdSelectEvent.connect(self.svdSelectEvent) #These should probably be placed somewhere else but oh well def get_selected_label(self): if self.viewer is not None: return self.viewer.selected_label() else: return None def setup_choosers(self, canonical=[]): for chooser in (self.x_chooser, self.y_chooser): chooser.clear() pcs = ["", "Default"] + ["Axis %d" % i for i in xrange(self.viewer.k)] chooser.insertItems(0, pcs) chooser.insertItems(2, canonical) # FIXME: why doesn't this work anymore? #chooser.setCompleter(QCompleter(self.viewer.labels)) chooser.setCurrentIndex(1) def update_choosers(self): matrix = self.viewer.projection.target_matrix xmags = np.sort(matrix[:,0]) xarg = np.argmax(matrix[:,0]) ymags = np.sort(matrix[:,1]) yarg = np.argmax(matrix[:,1]) if xmags[-1] > 10*xmags[-2]: self.x_chooser.setCurrentIndex(self.x_chooser.findText("Axis %d" % xarg)) else: self.x_chooser.setCurrentIndex(0) if ymags[-1] > 10*ymags[-2]: self.y_chooser.setCurrentIndex(self.y_chooser.findText("Axis %d" % yarg)) else: self.y_chooser.setCurrentIndex(0) @QtCore.pyqtSlot(str) def set_x_from_string(self, string): self.set_axis_from_string(0, string) @QtCore.pyqtSlot(str) def set_y_from_string(self, string): self.set_axis_from_string(1, string) def set_axis_from_string(self, axis, string): if self.viewer is not None: axismatch = SVDViewPanel.axis_re.search(string) if axismatch: # This describes a particular principal component pc = int(axismatch.group(1)) self.viewer.set_axis_to_pc(axis, pc) elif string == 'Default': if axis == 0: self.viewer.set_default_x_axis() if axis == 1: self.viewer.set_default_y_axis() else: self.viewer.set_axis_to_text(axis, string) def next_axis(self): if self.viewer is not None: if (self.x_chooser.currentIndex() == 1 and self.y_chooser.currentIndex() == 1): self.first_two_axes() else: self.viewer.projection.next_axis() self.viewer.activate_timer() def prev_axis(self): if self.viewer is not None: if (self.x_chooser.currentIndex() == 1 and self.y_chooser.currentIndex() == 1): self.first_two_axes() else: self.viewer.projection.prev_axis() self.viewer.activate_timer() def first_two_axes(self): """Go from the default projection to axes 0 and 1. Yes, those are different.""" self.set_axis_from_string(0, "Axis 0") self.set_axis_from_string(1, "Axis 1") self.update_choosers() def deactivate(self): if self.viewer is not None: self.viewer.projection.rotated.disconnect(self.update_choosers) self.viewer.svdSelectEvent.disconnect(self.svdSelectEvent) self.viewer.hide() del self.viewer self.viewer = None def reset_view(self): if self.viewer is not None: self.viewer.reset_view() self.x_chooser.setCurrentIndex(self.x_chooser.findText("Default")) self.y_chooser.setCurrentIndex(self.y_chooser.findText("Default")) self.viewer.activate_timer() def write_svg(self, filename): if self.viewer is not None: self.viewer.write_svg(filename) def focus_on_point(self, text): if self.viewer is not None: self.viewer.focus_on_point(text) self.viewer.activate_timer() def sizeHint(self): return QSize(600, 800) def find_point(self, string): string = unicode(string) if self.viewer is not None: if string in self.viewer.labels: self.focus_on_point(string) return True else: return False
class Interface(QWidget): """Interface widget class.""" def __init__(self, parent): super(Interface, self).__init__() self._preferences, vbox = parent, QVBoxLayout(self) self.toolbar_settings = settings.TOOLBAR_ITEMS groupBoxExplorer = QGroupBox( translations.TR_PREFERENCES_INTERFACE_EXPLORER_PANEL) #groupBoxToolbar = QGroupBox( #translations.TR_PREFERENCES_INTERFACE_TOOLBAR_CUSTOMIZATION) groupBoxLang = QGroupBox( translations.TR_PREFERENCES_INTERFACE_LANGUAGE) #Explorer vboxExplorer = QVBoxLayout(groupBoxExplorer) self._checkProjectExplorer = QCheckBox( translations.TR_PREFERENCES_SHOW_EXPLORER) self._checkSymbols = QCheckBox( translations.TR_PREFERENCES_SHOW_SYMBOLS) self._checkWebInspetor = QCheckBox( translations.TR_PREFERENCES_SHOW_WEB_INSPECTOR) self._checkFileErrors = QCheckBox( translations.TR_PREFERENCES_SHOW_FILE_ERRORS) self._checkMigrationTips = QCheckBox( translations.TR_PREFERENCES_SHOW_MIGRATION) vboxExplorer.addWidget(self._checkProjectExplorer) vboxExplorer.addWidget(self._checkSymbols) vboxExplorer.addWidget(self._checkWebInspetor) vboxExplorer.addWidget(self._checkFileErrors) vboxExplorer.addWidget(self._checkMigrationTips) #GUI - Toolbar #vbox_toolbar = QVBoxLayout(groupBoxToolbar) #hbox_select_items = QHBoxLayout() #label_toolbar = QLabel(translations.TR_PREFERENCES_TOOLBAR_ITEMS) #label_toolbar.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) #hbox_select_items.addWidget(label_toolbar) #self._comboToolbarItems = QComboBox() #self._load_combo_data(self._comboToolbarItems) #self._btnItemAdd = QPushButton(QIcon(":img/add"), '') #self._btnItemAdd.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) #self._btnItemAdd.setIconSize(QSize(16, 16)) #self._btnItemRemove = QPushButton(QIcon(':img/delete'), '') #self._btnItemRemove.setIconSize(QSize(16, 16)) #self._btnDefaultItems = QPushButton( #translations.TR_PREFERENCES_TOOLBAR_DEFAULT) #self._btnDefaultItems.setSizePolicy(QSizePolicy.Fixed, #QSizePolicy.Fixed) #self._btnItemRemove.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) #hbox_select_items.addWidget(self._comboToolbarItems) #hbox_select_items.addWidget(self._btnItemAdd) #hbox_select_items.addWidget(self._btnItemRemove) #hbox_select_items.addWidget(self._btnDefaultItems) #vbox_toolbar.addLayout(hbox_select_items) #self._toolbar_items = QToolBar() #self._toolbar_items.setObjectName("custom") #self._toolbar_items.setToolButtonStyle(Qt.ToolButtonIconOnly) #self._load_toolbar() #vbox_toolbar.addWidget(self._toolbar_items) #vbox_toolbar.addWidget(QLabel( #translations.TR_PREFERENCES_TOOLBAR_CONFIG_HELP)) #Language vboxLanguage = QVBoxLayout(groupBoxLang) vboxLanguage.addWidget(QLabel( translations.TR_PREFERENCES_SELECT_LANGUAGE)) self._comboLang = QComboBox() self._comboLang.setEnabled(False) vboxLanguage.addWidget(self._comboLang) vboxLanguage.addWidget(QLabel( translations.TR_PREFERENCES_REQUIRES_RESTART)) #Load Languages self._load_langs() #Settings self._checkProjectExplorer.setChecked( settings.SHOW_PROJECT_EXPLORER) self._checkSymbols.setChecked(settings.SHOW_SYMBOLS_LIST) self._checkWebInspetor.setChecked(settings.SHOW_WEB_INSPECTOR) self._checkFileErrors.setChecked(settings.SHOW_ERRORS_LIST) self._checkMigrationTips.setChecked(settings.SHOW_MIGRATION_LIST) vbox.addWidget(groupBoxExplorer) #vbox.addWidget(groupBoxToolbar) vbox.addWidget(groupBoxLang) #Signals #self.connect(self._btnItemAdd, SIGNAL("clicked()"), #self.toolbar_item_added) #self.connect(self._btnItemRemove, SIGNAL("clicked()"), #self.toolbar_item_removed) #self.connect(self._btnDefaultItems, SIGNAL("clicked()"), #self.toolbar_items_default) self.connect(self._preferences, SIGNAL("savePreferences()"), self.save) #def toolbar_item_added(self): #data = self._comboToolbarItems.itemData( #self._comboToolbarItems.currentIndex()) #if data not in self.toolbar_settings or data == 'separator': #selected = self.actionGroup.checkedAction() #if selected is None: #self.toolbar_settings.append(data) #else: #dataAction = selected.data() #self.toolbar_settings.insert( #self.toolbar_settings.index(dataAction) + 1, data) #self._load_toolbar() ## def toolbar_item_removed(self): #data = self._comboToolbarItems.itemData( #self._comboToolbarItems.currentIndex()) #if data in self.toolbar_settings and data != 'separator': #self.toolbar_settings.pop(self.toolbar_settings.index(data)) #self._load_toolbar() #elif data == 'separator': #self.toolbar_settings.reverse() #self.toolbar_settings.pop(self.toolbar_settings.index(data)) #self.toolbar_settings.reverse() #self._load_toolbar() ## def toolbar_items_default(self): #self.toolbar_settings = settings.TOOLBAR_ITEMS_DEFAULT #self._load_toolbar() ## def _load_combo_data(self, combo): #self.toolbar_items = { #'separator': [QIcon(':img/separator'), 'Add Separtor'], #'new-file': [QIcon(resources.IMAGES['new']), self.tr('New File')], #'new-project': [QIcon(resources.IMAGES['newProj']), #self.tr('New Project')], #'save-file': [QIcon(resources.IMAGES['save']), #self.tr('Save File')], #'save-as': [QIcon(resources.IMAGES['saveAs']), self.tr('Save As')], #'save-all': [QIcon(resources.IMAGES['saveAll']), #self.tr('Save All')], #'save-project': [QIcon(resources.IMAGES['saveAll']), #self.tr('Save Project')], #'reload-file': [QIcon(resources.IMAGES['reload-file']), #self.tr('Reload File')], #'open-file': [QIcon(resources.IMAGES['open']), #self.tr('Open File')], #'open-project': [QIcon(resources.IMAGES['openProj']), #self.tr('Open Project')], #'activate-profile': [QIcon(resources.IMAGES['activate-profile']), #self.tr('Activate Profile')], #'deactivate-profile': #[QIcon(resources.IMAGES['deactivate-profile']), #self.tr('Deactivate Profile')], #'print-file': [QIcon(resources.IMAGES['print']), #self.tr('Print File')], #'close-file': #[self.style().standardIcon(QStyle.SP_DialogCloseButton), #self.tr('Close File')], #'close-projects': #[self.style().standardIcon(QStyle.SP_DialogCloseButton), #self.tr('Close Projects')], #'undo': [QIcon(resources.IMAGES['undo']), self.tr('Undo')], #'redo': [QIcon(resources.IMAGES['redo']), self.tr('Redo')], #'cut': [QIcon(resources.IMAGES['cut']), self.tr('Cut')], #'copy': [QIcon(resources.IMAGES['copy']), self.tr('Copy')], #'paste': [QIcon(resources.IMAGES['paste']), self.tr('Paste')], #'find': [QIcon(resources.IMAGES['find']), self.tr('Find')], #'find-replace': [QIcon(resources.IMAGES['findReplace']), #self.tr('Find/Replace')], #'find-files': [QIcon(resources.IMAGES['find']), #self.tr('Find In files')], #'code-locator': [QIcon(resources.IMAGES['locator']), #self.tr('Code Locator')], #'splith': [QIcon(resources.IMAGES['splitH']), #self.tr('Split Horizontally')], #'splitv': [QIcon(resources.IMAGES['splitV']), #self.tr('Split Vertically')], #'follow-mode': [QIcon(resources.IMAGES['follow']), #self.tr('Follow Mode')], #'zoom-in': [QIcon(resources.IMAGES['zoom-in']), self.tr('Zoom In')], #'zoom-out': [QIcon(resources.IMAGES['zoom-out']), #self.tr('Zoom Out')], #'indent-more': [QIcon(resources.IMAGES['indent-more']), #self.tr('Indent More')], #'indent-less': [QIcon(resources.IMAGES['indent-less']), #self.tr('Indent Less')], #'comment': [QIcon(resources.IMAGES['comment-code']), #self.tr('Comment')], #'uncomment': [QIcon(resources.IMAGES['uncomment-code']), #self.tr('Uncomment')], #'go-to-definition': [QIcon(resources.IMAGES['go-to-definition']), #self.tr('Go To Definition')], #'insert-import': [QIcon(resources.IMAGES['insert-import']), #self.tr('Insert Import')], #'run-project': [QIcon(resources.IMAGES['play']), 'Run Project'], #'run-file': [QIcon(resources.IMAGES['file-run']), 'Run File'], #'stop': [QIcon(resources.IMAGES['stop']), 'Stop'], #'preview-web': [QIcon(resources.IMAGES['preview-web']), #self.tr('Preview Web')]} #for item in self.toolbar_items: #combo.addItem(self.toolbar_items[item][0], #self.toolbar_items[item][1], item) #combo.model().sort(0) ## def _load_toolbar(self): #pass ##self._toolbar_items.clear() ##self.actionGroup = QActionGroup(self) ##self.actionGroup.setExclusive(True) ##for item in self.toolbar_settings: ##if item == 'separator': ##self._toolbar_items.addSeparator() ##else: ##action = self._toolbar_items.addAction( ##self.toolbar_items[item][0], self.toolbar_items[item][1]) ##action.setData(item) ##action.setCheckable(True) ##self.actionGroup.addAction(action) def _load_langs(self): langs = file_manager.get_files_from_folder( resources.LANGS, '.qm') self._languages = ['English'] + \ [file_manager.get_module_name(lang) for lang in langs] self._comboLang.addItems(self._languages) if(self._comboLang.count() > 1): self._comboLang.setEnabled(True) if settings.LANGUAGE: index = self._comboLang.findText(settings.LANGUAGE) else: index = 0 self._comboLang.setCurrentIndex(index) def save(self): qsettings = IDE.ninja_settings() settings.TOOLBAR_ITEMS = self.toolbar_settings lang = self._comboLang.currentText() #preferences/interface qsettings.setValue('preferences/interface/showProjectExplorer', self._checkProjectExplorer.isChecked()) settings.SHOW_PROJECT_EXPLORER = self._checkProjectExplorer.isChecked() qsettings.setValue('preferences/interface/showSymbolsList', self._checkSymbols.isChecked()) settings.SHOW_SYMBOLS_LIST = self._checkSymbols.isChecked() qsettings.setValue('preferences/interface/showWebInspector', self._checkWebInspetor.isChecked()) settings.SHOW_WEB_INSPECTOR = self._checkWebInspetor.isChecked() qsettings.setValue('preferences/interface/showErrorsList', self._checkFileErrors.isChecked()) settings.SHOW_ERRORS_LIST = self._checkFileErrors.isChecked() qsettings.setValue('preferences/interface/showMigrationList', self._checkMigrationTips.isChecked()) settings.SHOW_MIGRATION_LIST = self._checkMigrationTips.isChecked() #qsettings.setValue('preferences/interface/toolbar', #settings.TOOLBAR_ITEMS) qsettings.setValue('preferences/interface/language', lang) lang = lang + '.qm' settings.LANGUAGE = os.path.join(resources.LANGS, lang)
class SkinsTab(QWidget): def __init__(self): QWidget.__init__(self) vbox = QVBoxLayout(self) #Top Bar hbox = QHBoxLayout() self.radioDefault = QRadioButton("Default Skin") self.radioCustom = QRadioButton("Custom") self.comboSkins = QComboBox() self.skins = loader.load_gui_skins() for item in self.skins: self.comboSkins.addItem(item) hbox.addWidget(self.radioDefault) hbox.addWidget(self.radioCustom) hbox.addWidget(self.comboSkins) #Text Area self.txtStyle = QPlainTextEdit() self.txtStyle.setReadOnly(True) #Settings settings = QSettings() settings.beginGroup('preferences') settings.beginGroup('skins') if settings.value('default', True).toBool(): self.radioDefault.setChecked(True) self.comboSkins.setEnabled(False) else: self.radioCustom.setChecked(True) index = self.comboSkins.findText(settings.value('selectedSkin', '').toString()) self.comboSkins.setCurrentIndex(index) content = self.skins[str(self.comboSkins.currentText())] self.txtStyle.setPlainText(content) settings.endGroup() settings.endGroup() vbox.addLayout(hbox) vbox.addWidget(self.txtStyle) vbox.addWidget(QLabel('Requires restart the IDE')) #Signals self.connect(self.radioDefault, SIGNAL("clicked()"), self._default_clicked) self.connect(self.radioCustom, SIGNAL("clicked()"), self._custom_clicked) def _default_clicked(self): self.comboSkins.setEnabled(False) self.txtStyle.setPlainText('') def _custom_clicked(self): self.comboSkins.setEnabled(True) content = self.skins[str(self.comboSkins.currentText())] self.txtStyle.setPlainText(content) def save(self): settings = QSettings() settings.beginGroup('preferences') settings.beginGroup('skins') settings.setValue('default', self.radioDefault.isChecked()) settings.setValue('selectedSkin', self.comboSkins.currentText()) settings.endGroup() settings.endGroup()
class preferencesDialog(QDialog): newMailerMessage = QtCore.Signal(str, str) def __init__(self, parent): QDialog.__init__(self, parent) self.tmpPref = {} self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref']) self.currLocale = self.parent().prm['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) self.audioManager = parent.audioManager self.mailer = emailSender(self) self.newMailerMessage.connect(self.popMailerMessage) self.tabWidget = QTabWidget() self.tabWidget.currentChanged.connect(self.tabChanged) self.appPrefWidget = QWidget() self.soundPrefWidget = QWidget() self.notificationPrefWidget = QWidget() self.eegPrefWidget = QWidget() #the gui widget for these are in an external dialog self.wavsPref = {} self.wavsPref['endMessageFiles'] = self.tmpPref['pref']['general']['endMessageFiles'] self.wavsPref['endMessageFilesUse'] = self.tmpPref['pref']['general']['endMessageFilesUse'] self.wavsPref['endMessageFilesID'] = self.tmpPref['pref']['general']['endMessageFilesID'] self.wavsPref['endMessageLevels'] = self.tmpPref['pref']['general']['endMessageLevels'] #GENERAL PREF appPrefGrid = QGridLayout() n = 0 self.languageChooserLabel = QLabel(self.tr('Language (requires restart):')) appPrefGrid.addWidget(self.languageChooserLabel, n, 0) self.languageChooser = QComboBox() self.languageChooser.addItems(self.parent().prm['appData']['available_languages']) self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language'])) self.languageChooser.currentIndexChanged[int].connect(self.onLanguageChooserChange) appPrefGrid.addWidget(self.languageChooser, n, 1) n = n+1 self.countryChooserLabel = QLabel(self.tr('Country (requires restart):')) appPrefGrid.addWidget(self.countryChooserLabel, n, 0) self.countryChooser = QComboBox() self.countryChooser.addItems(self.parent().prm['appData']['available_countries'][self.tmpPref['pref']['language']]) self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country'])) appPrefGrid.addWidget(self.countryChooser, n, 1) n = n+1 self.responseBoxLanguageChooserLabel = QLabel(self.tr('Response Box Language (requires restart):')) appPrefGrid.addWidget(self.responseBoxLanguageChooserLabel, n, 0) self.responseBoxLanguageChooser = QComboBox() self.responseBoxLanguageChooser.addItems(self.parent().prm['appData']['available_languages']) self.responseBoxLanguageChooser.setCurrentIndex(self.responseBoxLanguageChooser.findText(self.tmpPref['pref']['responseBoxLanguage'])) self.responseBoxLanguageChooser.currentIndexChanged[int].connect(self.onResponseBoxLanguageChooserChange) appPrefGrid.addWidget(self.responseBoxLanguageChooser, n, 1) n = n+1 self.responseBoxCountryChooserLabel = QLabel(self.tr('Response Box Country (requires restart):')) appPrefGrid.addWidget(self.responseBoxCountryChooserLabel, n, 0) self.responseBoxCountryChooser = QComboBox() self.responseBoxCountryChooser.addItems(self.parent().prm['appData']['available_countries'][self.tmpPref['pref']['responseBoxLanguage']]) self.responseBoxCountryChooser.setCurrentIndex(self.responseBoxCountryChooser.findText(self.tmpPref['pref']['responseBoxCountry'])) appPrefGrid.addWidget(self.responseBoxCountryChooser, n, 1) n = n+1 self.csvSeparatorLabel = QLabel(self.tr('csv separator:')) appPrefGrid.addWidget(self.csvSeparatorLabel, n, 0) self.csvSeparatorWidget = QLineEdit(self.tmpPref['pref']["general"]["csvSeparator"]) appPrefGrid.addWidget(self.csvSeparatorWidget, n, 1) n = n+1 self.listenerNameWarnCheckBox = QCheckBox(self.tr('Warn if listener name missing')) self.listenerNameWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["listenerNameWarn"]) appPrefGrid.addWidget(self.listenerNameWarnCheckBox, n, 0) n = n+1 self.sessionLabelWarnCheckBox = QCheckBox(self.tr('Warn if session label missing')) self.sessionLabelWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["sessionLabelWarn"]) appPrefGrid.addWidget(self.sessionLabelWarnCheckBox, n, 0) n = n+1 self.dpCorrCheckBox = QCheckBox(self.tr('d-prime correction')) self.dpCorrCheckBox.setChecked(self.tmpPref['pref']['general']['dprimeCorrection']) self.dpCorrCheckBox.setWhatsThis(self.tr("If checked, when automatically processing result files, convert hit rates of 0 and 1 to 1/2N and 1-1/(2N) respectively, where N is the number of trials, to avoid infinite values of d'")) appPrefGrid.addWidget(self.dpCorrCheckBox, n, 0) n = n+1 self.recursionLimitLabel = QLabel(self.tr('Max Recursion Depth (requires restart):')) appPrefGrid.addWidget(self.recursionLimitLabel, n, 0) self.recursionLimitWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["maxRecursionDepth"])) self.recursionLimitWidget.setValidator(QIntValidator(self)) appPrefGrid.addWidget(self.recursionLimitWidget, n, 1) n = n+1 n = n+1 self.startupCommandLabel = QLabel(self.tr('Execute command at startup:')) appPrefGrid.addWidget(self.startupCommandLabel, n, 0) self.startupCommandWidget = QLineEdit(self.tmpPref["pref"]["general"]["startupCommand"]) appPrefGrid.addWidget(self.startupCommandWidget, n, 1) n = n+1 self.appPrefWidget.setLayout(appPrefGrid) self.appPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize) #SOUND PREF soundPrefGrid = QGridLayout() n = 0 self.playChooser = QComboBox() self.playChooser.addItems(self.parent().prm['appData']['available_play_commands']) self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['sound']['playCommandType'])) self.playChooser.currentIndexChanged[int].connect(self.onPlayChooserChange) self.playChooserLabel = QLabel(self.tr('Play Command:')) soundPrefGrid.addWidget(self.playChooserLabel, 0, 0) soundPrefGrid.addWidget(self.playChooser, 0, 1) n = n+1 self.playCommandLabel = QLabel(self.tr('Command:')) soundPrefGrid.addWidget(self.playCommandLabel, n, 0) self.playCommandWidget = QLineEdit(self.tmpPref['pref']['sound']['playCommand']) if self.playChooser.currentText() != self.tr('custom'): self.playCommandWidget.setReadOnly(True) soundPrefGrid.addWidget(self.playCommandWidget, n, 1) n = n+1 foo = self.playChooser.currentText() if foo != self.tr('custom'): self.playCommandLabel.hide() self.playCommandWidget.hide() #if alsaaudio is selected, provide device list chooser if self.parent().prm["appData"]["alsaaudioAvailable"] == True: self.alsaaudioPlaybackCardList = self.listAlsaaudioPlaybackCards() self.alsaaudioDeviceLabel = QLabel(self.tr('Device:')) soundPrefGrid.addWidget(self.alsaaudioDeviceLabel, n, 0) self.alsaaudioDeviceChooser = QComboBox() self.alsaaudioDeviceChooser.addItems(self.alsaaudioPlaybackCardList) self.alsaaudioDeviceChooser.setCurrentIndex(self.alsaaudioDeviceChooser.findText(self.tmpPref["pref"]["sound"]["alsaaudioDevice"])) soundPrefGrid.addWidget(self.alsaaudioDeviceChooser, n, 1) n = n+1 if self.tmpPref['pref']['sound']['playCommandType'] != "alsaaudio": self.alsaaudioDeviceLabel.hide() self.alsaaudioDeviceChooser.hide() #if pyaudio is selected, provide device list chooser if self.parent().prm["appData"]["pyaudioAvailable"] == True: self.listPyaudioPlaybackDevices() self.pyaudioDeviceLabel = QLabel(self.tr('Device:')) soundPrefGrid.addWidget(self.pyaudioDeviceLabel, n, 0) self.pyaudioDeviceChooser = QComboBox() self.pyaudioDeviceChooser.addItems(self.pyaudioDeviceListName) try: self.pyaudioDeviceChooser.setCurrentIndex(self.pyaudioDeviceListIdx.index(self.tmpPref["pref"]["sound"]["pyaudioDevice"])) except: self.tmpPref["pref"]["sound"]["pyaudioDevice"] = self.pyaudioDeviceListIdx[0] self.parent().prm["pref"]["sound"]["pyaudioDevice"] = self.pyaudioDeviceListIdx[0] self.pyaudioDeviceChooser.setCurrentIndex(self.pyaudioDeviceListIdx.index(self.tmpPref["pref"]["sound"]["pyaudioDevice"])) soundPrefGrid.addWidget(self.pyaudioDeviceChooser, n, 1) n = n+1 if self.tmpPref['pref']['sound']['playCommandType'] != "pyaudio": self.pyaudioDeviceLabel.hide() self.pyaudioDeviceChooser.hide() if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True: self.bufferSizeLabel = QLabel(self.tr('Buffer Size (samples):')) soundPrefGrid.addWidget(self.bufferSizeLabel, n, 0) self.bufferSizeWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["sound"]["bufferSize"])) self.bufferSizeWidget.setValidator(QIntValidator(self)) soundPrefGrid.addWidget(self.bufferSizeWidget, n, 1) n = n+1 if self.tmpPref['pref']['sound']['playCommandType'] not in ["alsaaudio", "pyaudio"]: self.bufferSizeLabel.hide() self.bufferSizeWidget.hide() self.samplerateLabel = QLabel(self.tr('Default Sampling Rate:')) soundPrefGrid.addWidget(self.samplerateLabel, n, 0) self.samplerateWidget = QLineEdit(self.tmpPref["pref"]["sound"]["defaultSampleRate"]) #self.samplerateWidget.setValidator(QIntValidator(self)) soundPrefGrid.addWidget(self.samplerateWidget, n, 1) n = n+1 self.nbitsLabel = QLabel(self.tr('Default Bits:')) self.nbitsChooser = QComboBox() self.nbitsChooser.addItems(self.parent().prm["nBitsChoices"]) self.nbitsChooser.setCurrentIndex(self.parent().prm["nBitsChoices"].index(self.tmpPref["pref"]["sound"]["defaultNBits"])) soundPrefGrid.addWidget(self.nbitsLabel, n, 0) soundPrefGrid.addWidget(self.nbitsChooser, n, 1) n = n+1 self.wavmanagerLabel = QLabel(self.tr('Wav Manager (requires restart):')) self.wavmanagerChooser = QComboBox() self.wavmanagerChooser.addItems(self.parent().prm['appData']['wavmanagers']) self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['sound']['wavmanager'])) soundPrefGrid.addWidget(self.wavmanagerLabel, n, 0) soundPrefGrid.addWidget(self.wavmanagerChooser, n, 1) n = n+1 self.writewav = QCheckBox(self.tr('Write wav file')) self.writewav.setChecked(self.tmpPref["pref"]["sound"]["writewav"]) soundPrefGrid.addWidget(self.writewav, n, 0) n = n+1 self.writeSndSeqSegments = QCheckBox(self.tr('Write sound sequence segments wavs')) self.writeSndSeqSegments.setChecked(self.tmpPref["pref"]["sound"]["writeSndSeqSegments"]) soundPrefGrid.addWidget(self.writeSndSeqSegments, n, 0) n = n+1 self.appendSilenceLabel = QLabel(self.tr('Append silence to each sound (ms):')) soundPrefGrid.addWidget(self.appendSilenceLabel, n, 0) self.appendSilenceWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["sound"]["appendSilence"])) soundPrefGrid.addWidget(self.appendSilenceWidget, n, 1) n = n+1 self.soundPrefWidget.setLayout(soundPrefGrid) self.soundPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize) # NOTIFICATION PREF notificationPrefGrid = QGridLayout() n = 0 self.playEndMessage = QCheckBox(self.tr('Play End Message')) self.playEndMessage.setChecked(self.tmpPref["pref"]["general"]["playEndMessage"]) notificationPrefGrid.addWidget(self.playEndMessage, n, 0) self.endMessageButton = QPushButton(self.tr("Choose Wav"), self) self.endMessageButton.clicked.connect(self.onClickEndMessageButton) notificationPrefGrid.addWidget(self.endMessageButton, n, 1) n = n+1 notificationPrefGrid.addItem(QSpacerItem(20,20,QSizePolicy.Expanding), n, 0) n = n+1 self.nBlocksLabel = QLabel(self.tr('blocks before end of experiment:')) notificationPrefGrid.addWidget(self.nBlocksLabel, n, 1) self.nBlocksWidget = QLineEdit(self.currLocale.toString(self.tmpPref['pref']['email']['nBlocksNotify'])) notificationPrefGrid.addWidget(self.nBlocksWidget, n, 0) n = n+1 self.emailNotify = QCheckBox(self.tr('Send Notification e-mail')) self.emailNotify.setChecked(self.tmpPref["pref"]["email"]["notifyEnd"]) notificationPrefGrid.addWidget(self.emailNotify, n, 0) n = n+1 self.nBlocksCustomCommandLabel = QLabel(self.tr('Execute custom command:')) notificationPrefGrid.addWidget(self.nBlocksCustomCommandLabel, n, 0) self.nBlocksCustomCommandWidget = QLineEdit(self.tmpPref["pref"]["general"]["nBlocksCustomCommand"]) notificationPrefGrid.addWidget(self.nBlocksCustomCommandWidget, n, 1) n = n+1 notificationPrefGrid.addItem(QSpacerItem(20,20,QSizePolicy.Expanding), n, 0) n = n+1 self.atEndLabel = QLabel(self.tr('At the end of the experiment:')) notificationPrefGrid.addWidget(self.atEndLabel, n, 0) n = n+1 self.sendData = QCheckBox(self.tr('Send data via e-mail')) self.sendData.setChecked(self.tmpPref["pref"]["email"]["sendData"]) notificationPrefGrid.addWidget(self.sendData, n, 0) n = n+1 self.atEndCustomCommandLabel = QLabel(self.tr('Execute custom command:')) notificationPrefGrid.addWidget(self.atEndCustomCommandLabel, n, 0) self.atEndCustomCommandWidget = QLineEdit(self.tmpPref["pref"]["general"]["atEndCustomCommand"]) notificationPrefGrid.addWidget(self.atEndCustomCommandWidget, n, 1) n = n+1 notificationPrefGrid.addItem(QSpacerItem(20,20,QSizePolicy.Expanding), n, 0) n = n+1 self.serverLabel = QLabel(self.tr('Outgoing server (SMTP):')) notificationPrefGrid.addWidget(self.serverLabel, n, 0) self.serverWidget = QLineEdit(self.tmpPref['pref']['email']['SMTPServer']) notificationPrefGrid.addWidget(self.serverWidget, n, 1) n = n+1 self.serverPortLabel = QLabel(self.tr('Port:')) notificationPrefGrid.addWidget(self.serverPortLabel, n, 0) self.serverPortWidget = QLineEdit(self.currLocale.toString(self.tmpPref['pref']['email']['SMTPServerPort'])) self.serverPortWidget.setValidator(QIntValidator(self)) notificationPrefGrid.addWidget(self.serverPortWidget, n, 1) n = n+1 self.serverSecurityLabel = QLabel(self.tr('Security:')) notificationPrefGrid.addWidget(self.serverSecurityLabel, n, 0) self.serverSecurityChooser = QComboBox() self.serverSecurityChooser.addItems(["TLS/SSL (a)", "TLS/SSL (b)", "none"]) self.serverSecurityChooser.setCurrentIndex(self.serverSecurityChooser.findText(self.tmpPref['pref']['email']['SMTPServerSecurity'])) notificationPrefGrid.addWidget(self.serverSecurityChooser, n, 1) n = n+1 self.serverRequiresAuthCheckBox = QCheckBox(self.tr('Server requires authentication')) self.serverRequiresAuthCheckBox.setChecked(self.tmpPref["pref"]["email"]["serverRequiresAuthentication"]) notificationPrefGrid.addWidget(self.serverRequiresAuthCheckBox, n, 0, 1, 2) n = n+1 self.usernameLabel = QLabel(self.tr('Username:'******'pref']['email']['fromUsername']) notificationPrefGrid.addWidget(self.usernameWidget, n, 1) n = n+1 self.passwordLabel = QLabel(self.tr('Password:'******'pref']['email']['fromPassword']) self.passwordWidget.setEchoMode(QLineEdit.Password) notificationPrefGrid.addWidget(self.passwordWidget, n, 1) n = n+1 self.passwordWarningLabel = QLabel(self.tr('Password is NOT stored safely (see manual), use at your own risk!')) notificationPrefGrid.addWidget(self.passwordWarningLabel, n, 0, 1, 2) n = n+1 self.testEmailButton = QPushButton(self.tr("Send test e-mail"), self) self.testEmailButton.clicked.connect(self.onClickTestEmailButton) self.testEmailButton.setToolTip(self.tr("Send a test e-mail")) notificationPrefGrid.addWidget(self.testEmailButton, n, 0, 1, 2) self.notificationPrefWidget.setLayout(notificationPrefGrid) self.notificationPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize) ##--#--#--#--#-- # EEG PREF GRID eegPrefGrid = QGridLayout() n = 0 self.ONTriggerLabel = QLabel(self.tr('ON Trigger:')) eegPrefGrid.addWidget(self.ONTriggerLabel, n, 0) self.ONTriggerWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["ONTrigger"])) eegPrefGrid.addWidget(self.ONTriggerWidget, n, 1) n = n+1 self.OFFTriggerLabel = QLabel(self.tr('OFF Trigger:')) eegPrefGrid.addWidget(self.OFFTriggerLabel, n, 0) self.OFFTriggerWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["OFFTrigger"])) eegPrefGrid.addWidget(self.OFFTriggerWidget, n, 1) n = n+1 self.triggerDurLabel = QLabel(self.tr('Trigger Duration (ms):')) eegPrefGrid.addWidget(self.triggerDurLabel, n, 0) self.triggerDurWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["triggerDur"])) eegPrefGrid.addWidget(self.triggerDurWidget, n, 1) self.eegPrefWidget.setLayout(eegPrefGrid) self.eegPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize) # ........................ self.tabWidget.addTab(self.appPrefWidget, self.tr("Genera&l")) self.tabWidget.addTab(self.soundPrefWidget, self.tr("Soun&d")) self.tabWidget.addTab(self.notificationPrefWidget, self.tr("Notification&s")) self.tabWidget.addTab(self.eegPrefWidget, self.tr("EE&G")) buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Ok|QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.permanentApply) layout = QVBoxLayout() layout.addWidget(self.tabWidget) layout.addWidget(buttonBox) self.setLayout(layout) def onLanguageChooserChange(self): for i in range(self.countryChooser.count()): self.countryChooser.removeItem(0) self.countryChooser.addItems(self.parent().prm['appData']['available_countries'][self.languageChooser.currentText()]) def onResponseBoxLanguageChooserChange(self): for i in range(self.responseBoxCountryChooser.count()): self.responseBoxCountryChooser.removeItem(0) self.responseBoxCountryChooser.addItems(self.parent().prm['appData']['available_countries'][self.responseBoxLanguageChooser.currentText()]) def onPlayChooserChange(self): foo = self.playChooser.currentText() if foo != self.tr('custom'): self.playCommandLabel.hide() self.playCommandWidget.hide() self.playCommandWidget.setText(foo) self.playCommandWidget.setReadOnly(True) else: self.playCommandWidget.show() self.playCommandLabel.show() self.playCommandWidget.setReadOnly(False) if self.parent().prm["appData"]["alsaaudioAvailable"] == True: if foo == "alsaaudio": self.alsaaudioDeviceLabel.show() self.alsaaudioDeviceChooser.show() else: self.alsaaudioDeviceLabel.hide() self.alsaaudioDeviceChooser.hide() if self.parent().prm["appData"]["pyaudioAvailable"] == True: if foo == "pyaudio": self.pyaudioDeviceLabel.show() self.pyaudioDeviceChooser.show() else: self.pyaudioDeviceLabel.hide() self.pyaudioDeviceChooser.hide() if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True: if foo in ["alsaaudio", "pyaudio"]: self.bufferSizeLabel.show() self.bufferSizeWidget.show() else: self.bufferSizeLabel.hide() self.bufferSizeWidget.hide() def onClickEndMessageButton(self): dialog = wavListDialog(self) if dialog.exec_(): self.wavsList = dialog.wavsList self.wavsPref = {} self.wavsPref['endMessageFiles'] = [] self.wavsPref['endMessageFilesUse'] = [] self.wavsPref['endMessageFilesID'] = [] self.wavsPref['endMessageLevels'] = [] keys = sorted(self.wavsList.keys()) for key in keys: self.wavsPref['endMessageFiles'].append(str(self.wavsList[key]['file'])) self.wavsPref['endMessageFilesUse'].append(self.wavsList[key]['use']) self.wavsPref['endMessageLevels'].append(self.wavsList[key]['level']) self.wavsPref['endMessageFilesID'].append(key) def onClickTestEmailButton(self): self.mailer.sendTestEmail() def popMailerMessage(self, msg, msgtype): if msgtype == 'critical': QMessageBox.critical(self, self.tr("Error"), msg) elif msgtype == 'warning': QMessageBox.warning(self, self.tr("Warning"), msg) elif msgtype == 'information': QMessageBox.information(self, self.tr("Information"), msg) def tryApply(self): self.tmpPref['pref']['language'] = self.tr(self.languageChooser.currentText()) self.tmpPref['pref']['country'] = self.tr(self.countryChooser.currentText()) self.tmpPref['pref']['responseBoxLanguage'] = self.tr(self.responseBoxLanguageChooser.currentText()) self.tmpPref['pref']['responseBoxCountry'] = self.tr(self.responseBoxCountryChooser.currentText()) self.tmpPref['pref']['general']['csvSeparator'] = self.csvSeparatorWidget.text() self.tmpPref['pref']['general']['ONTrigger'] = self.currLocale.toInt(self.ONTriggerWidget.text())[0] self.tmpPref['pref']['general']['OFFTrigger'] = self.currLocale.toInt(self.OFFTriggerWidget.text())[0] self.tmpPref['pref']['general']['triggerDur'] = self.currLocale.toDouble(self.triggerDurWidget.text())[0] self.tmpPref['pref']['general']['maxRecursionDepth'] = self.currLocale.toInt(self.recursionLimitWidget.text())[0] self.tmpPref['pref']['general']['startupCommand'] = self.startupCommandWidget.text() self.tmpPref['pref']['sound']['playCommand'] = self.tr(self.playCommandWidget.text()) self.tmpPref['pref']['sound']['playCommandType'] = self.tr(self.playChooser.currentText()) if self.parent().prm["appData"]["alsaaudioAvailable"] == True: self.tmpPref['pref']['sound']['alsaaudioDevice'] = self.alsaaudioDeviceChooser.currentText() if self.parent().prm["appData"]["pyaudioAvailable"] == True: self.tmpPref['pref']['sound']['pyaudioDevice'] = self.pyaudioDeviceListIdx[self.pyaudioDeviceChooser.currentIndex()] self.tmpPref['pref']['sound']['wavmanager'] = str(self.wavmanagerChooser.currentText()) if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True: self.tmpPref['pref']['sound']['bufferSize'] = self.currLocale.toInt(self.bufferSizeWidget.text())[0] self.tmpPref['pref']['sound']['defaultSampleRate'] = self.samplerateWidget.text() self.tmpPref['pref']['sound']['defaultNBits'] = self.nbitsChooser.currentText() self.tmpPref['pref']['sound']['appendSilence'] = self.currLocale.toInt(self.appendSilenceWidget.text())[0] self.tmpPref["pref"]["email"]["nBlocksNotify"] = self.currLocale.toInt(self.nBlocksWidget.text())[0] self.tmpPref["pref"]["general"]["nBlocksCustomCommand"] = self.nBlocksCustomCommandWidget.text() self.tmpPref["pref"]["general"]["atEndCustomCommand"] = self.atEndCustomCommandWidget.text() self.tmpPref["pref"]["email"]['SMTPServer'] = self.serverWidget.text() self.tmpPref["pref"]["email"]['SMTPServerPort'] = self.currLocale.toInt(self.serverPortWidget.text())[0] self.tmpPref["pref"]["email"]['fromUsername'] = self.usernameWidget.text() self.tmpPref["pref"]["email"]['SMTPServerSecurity'] = self.serverSecurityChooser.currentText() self.tmpPref["pref"]["general"]["endMessageFiles"] = self.wavsPref['endMessageFiles'] self.tmpPref["pref"]["general"]["endMessageFilesUse"] = self.wavsPref['endMessageFilesUse'] self.tmpPref["pref"]["general"]["endMessageFilesID"] = self.wavsPref['endMessageFilesID'] self.tmpPref["pref"]["general"]["endMessageLevels"] = self.wavsPref['endMessageLevels'] self.tmpPref["pref"]["email"]['fromPassword'] = self.passwordWidget.text() if self.writewav.isChecked(): self.tmpPref['pref']['sound']['writewav'] = True else: self.tmpPref['pref']['sound']['writewav'] = False if self.writeSndSeqSegments.isChecked(): self.tmpPref['pref']['sound']['writeSndSeqSegments'] = True else: self.tmpPref['pref']['sound']['writeSndSeqSegments'] = False if self.dpCorrCheckBox.isChecked(): self.tmpPref['pref']['general']['dprimeCorrection'] = True else: self.tmpPref['pref']['general']['dprimeCorrection'] = False if self.listenerNameWarnCheckBox.isChecked(): self.tmpPref['pref']['general']['listenerNameWarn'] = True else: self.tmpPref['pref']['general']['listenerNameWarn'] = False if self.sessionLabelWarnCheckBox.isChecked(): self.tmpPref['pref']['general']['sessionLabelWarn'] = True else: self.tmpPref['pref']['general']['sessionLabelWarn'] = False if self.emailNotify.isChecked(): self.tmpPref['pref']['email']['notifyEnd'] = True else: self.tmpPref['pref']['email']['notifyEnd'] = False if self.sendData.isChecked(): self.tmpPref['pref']['email']['sendData'] = True else: self.tmpPref['pref']['email']['sendData'] = False if self.serverRequiresAuthCheckBox.isChecked(): self.tmpPref['pref']['email']['serverRequiresAuthentication'] = True else: self.tmpPref['pref']['email']['serverRequiresAuthentication'] = False if self.playEndMessage.isChecked(): self.tmpPref['pref']['general']['playEndMessage'] = True else: self.tmpPref['pref']['general']['playEndMessage'] = False if self.tmpPref['pref']['email']['notifyEnd'] == True or self.tmpPref['pref']['email']['sendData'] == True: if checkUsernameValid(self.tmpPref["pref"]["email"]['fromUsername']) == False: errMsg = self.tr("Username invalid. Disabling sending e-mails.") QMessageBox.warning(self, self.tr("Warning"), errMsg) self.emailNotify.setChecked(False) self.sendData.setChecked(False) self.tmpPref['pref']['email']['notifyEnd'] = False self.tmpPref['pref']['email']['sendData'] = False elif checkServerValid(self.tmpPref["pref"]["email"]['SMTPServer']) == False: errMsg = self.tr("SMTP server name invalid. Disabling sending e-mails.") QMessageBox.warning(self, self.tr("Warning"), errMsg) self.emailNotify.setChecked(False) self.sendData.setChecked(False) self.tmpPref['pref']['email']['notifyEnd'] = False self.tmpPref['pref']['email']['sendData'] = False def revertChanges(self): self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language'])) self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country'])) self.responseBoxLanguageChooser.setCurrentIndex(self.responseBoxLanguageChooser.findText(self.tmpPref['pref']['responseBoxLanguage'])) self.responseBoxCountryChooser.setCurrentIndex(self.responseBoxCountryChooser.findText(self.tmpPref['pref']['responseBoxCountry'])) self.csvSeparatorWidget.setText(self.tmpPref['pref']['general']['csvSeparator']) self.ONTriggerWidget.setText(self.currLocale.toString(self.tmpPref['pref']['general']['ONTrigger'])) self.OFFTriggerWidget.setText(self.currLocale.toString(self.tmpPref['pref']['general']['OFFTrigger'])) self.triggerDurWidget.setText(self.currLocale.toString(self.tmpPref['pref']['general']['triggerDur'])) self.recursionLimitWidget.setText(self.currLocale.toString(self.tmpPref['pref']['general']['maxRecursionDepth'])) self.startupCommandWidget.setText(self.tmpPref['pref']['general']['startupCommand']) self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['sound']['playCommandType'])) if self.parent().prm["appData"]["alsaaudioAvailable"] == True: self.alsaaudioDeviceChooser.setCurrentIndex(self.alsaaudioDeviceChooser.findText(self.tmpPref['pref']['sound']['alsaaudioDevice'])) if self.parent().prm["appData"]["pyaudioAvailable"] == True: self.pyaudioDeviceChooser.setCurrentIndex(self.pyaudioDeviceListIdx.index(self.tmpPref['pref']['sound']['pyaudioDevice'])) self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['sound']['wavmanager'])) self.playCommandWidget.setText(self.tmpPref['pref']['sound']['playCommand']) if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True: self.bufferSizeWidget.setText(self.currLocale.toString(self.tmpPref['pref']['sound']['bufferSize'])) self.samplerateWidget.setText(self.tmpPref['pref']['sound']['defaultSampleRate']) self.nbitsChooser.setCurrentIndex(self.nbitsChooser.findText(self.tmpPref['pref']['sound']['defaultNBits'])) self.appendSilenceWidget.setText(self.currLocale.toString(self.tmpPref['pref']['sound']['appendSilence'])) self.nBlocksWidget.setText(self.currLocale.toString(self.tmpPref['pref']['email']['nBlocksNotify'])) self.nBlocksCustomCommandWidget.setText( self.tmpPref["pref"]["general"]["nBlocksCustomCommand"]) self.atEndCustomCommandWidget.setText( self.tmpPref["pref"]["general"]["nBlocksCustomCommand"]) self.serverWidget.setText(self.tmpPref['pref']['email']['SMTPServer']) self.serverPortWidget.setText(self.currLocale.toString(self.tmpPref['pref']['email']['SMTPServerPort'])) self.usernameWidget.setText(self.tmpPref['pref']['email']['fromUsername']) self.passwordWidget.setText(self.tmpPref['pref']['email']['fromPassword']) self.serverSecurityChooser.setCurrentIndex(self.serverSecurityChooser.findText(self.tmpPref['pref']['email']['SMTPServerSecurity'])) self.wavsPref["endMessageFiles"] = self.tmpPref["pref"]["general"]["endMessageFiles"] self.wavsPref["endMessageFilesUse"] = self.tmpPref["pref"]["general"]["endMessageFilesUse"] self.wavsPref["endMessageFilesID"] = self.tmpPref["pref"]["general"]["endMessageFilesID"] self.wavsPref["endMessageLevels"] = self.tmpPref["pref"]["general"]["endMessageLevels"] if self.playChooser.currentText() != self.tr('custom'): self.playCommandWidget.setReadOnly(True) self.writewav.setChecked(self.tmpPref["pref"]["sound"]["writewav"]) self.writeSndSeqSegments.setChecked(self.tmpPref["pref"]["sound"]["writeSndSeqSegments"]) self.dpCorrCheckBox.setChecked(self.tmpPref["pref"]["general"]["dprimeCorrection"]) self.listenerNameWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["listenerNameWarn"]) self.sessionLabelWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["sessionLabelWarn"]) self.emailNotify.setChecked(self.tmpPref["pref"]["email"]["notifyEnd"]) self.sendData.setChecked(self.tmpPref["pref"]["email"]["sendData"]) self.serverRequiresAuthCheckBox.setChecked(self.tmpPref["pref"]["email"]["serverRequiresAuthentication"]) self.playEndMessage.setChecked(self.tmpPref["pref"]["general"]["playEndMessage"]) def permanentApply(self): self.tryApply() if self.parent().prm['pref']['email']['fromPassword'] != self.tmpPref['pref']['email']['fromPassword']: passwd = bytes(self.passwordWidget.text(),'utf-8') encoded_passwd = base64.b64encode(passwd) encoded_passwd = str(encoded_passwd, "utf-8") #passwd = hashlib.sha1(passwd).hexdigest() self.tmpPref["pref"]["email"]['fromPassword'] = encoded_passwd self.passwordWidget.setText(self.tmpPref['pref']['email']['fromPassword']) self.parent().prm['pref'] = copy.deepcopy(self.tmpPref['pref']) f = open(self.parent().prm['prefFile'], 'wb') pickle.dump(self.parent().prm['pref'], f) f.close() def tabChanged(self): self.tryApply() if self.tmpPref['pref'] != self.parent().prm['pref']: reply = QMessageBox.warning(self, self.tr("Warning"), self.tr('There are unsaved changes. Apply Changes?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if reply == QMessageBox.Yes: self.permanentApply() else: self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref']) self.revertChanges() def listAlsaaudioPlaybackCards(self): playbackCardList = [] for card in alsaaudio.cards(): try: alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, card=card) playbackCardList.append(card) except: pass return playbackCardList def listPyaudioPlaybackDevices(self): self.pyaudioHostApiListName = [] self.pyaudioHostApiListIdx = [] self.pyaudioDeviceListName = [] self.pyaudioDeviceListIdx = [] paManager = pyaudio.PyAudio() nDevices = paManager.get_device_count() nApi = paManager.get_host_api_count() for i in range(nApi): self.pyaudioHostApiListName.append(paManager.get_host_api_info_by_index(i)['name']) self.pyaudioHostApiListIdx.append(paManager.get_host_api_info_by_index(i)['index']) for i in range(nDevices): thisDevInfo = paManager.get_device_info_by_index(i) if thisDevInfo["maxOutputChannels"] > 0: self.pyaudioDeviceListName.append(thisDevInfo["name"] + ' - ' + self.pyaudioHostApiListName[thisDevInfo["hostApi"]]) self.pyaudioDeviceListIdx.append(thisDevInfo["index"]) return
def createGUIElements(self): ''' Build the GUI based on the parameters for the tool ''' for i, param in enumerate(self.tooltypearray): # print 'creatgui element %d, %s' %(i, param) #Swap in the passed params if they exist... loop through each passed #param and see if it matches... if so swap it in if self.optional_params.has_key(str(param[0])): param[2] = self.optional_params[str(param[0])] #print "Key: %s , Val: %s" % (param[0],param[1]) widgetTemp = QWidget(self.variableBox) widgetTemp.setObjectName(QString("test_widget").append(QString(i))) self.test_widget.append(widgetTemp) hlayout = QHBoxLayout(widgetTemp) self.hboxlayout.append(hlayout) hlayout.setMargin(4) hlayout.setSpacing(4) hlayout.setObjectName(QString("hboxlayout").append(QString(i))) test_text = QLabel(widgetTemp) self.test_text.append(test_text) test_text.setObjectName(QString("test_text").append(QString(i))) paramName = param[0].strip() if param[2].strip() == "Required": palette = test_text.palette() palette.setColor(QPalette.WindowText, Qt.red) test_text.setPalette(palette) test_text.setText(paramName) test_text_type = QLabel(widgetTemp) self.test_text_type.append(test_text_type) test_text_type.setObjectName( QString("test_text_type").append(QString(i))) paramName = param[1].strip() test_text_type.setText( QString("(").append(paramName).append(QString(")"))) hlayout.addWidget(test_text) hlayout.addWidget(test_text_type) if param[1] == 'db_connection_hook': test_line = QComboBox(widgetTemp) db_connection_choices = get_db_connection_names() for i in db_connection_choices: test_line.addItem(QString(i)) self.test_line.append(test_line) test_line.setEnabled(True) test_line.setMinimumSize(QSize(200, 0)) test_line.setObjectName( QString("test_line").append(QString(i))) index = test_line.findText(param[2], Qt.MatchExactly) test_line.setCurrentIndex(index) else: test_line = QLineEdit(widgetTemp) self.test_line.append(test_line) test_line.setEnabled(True) test_line.setMinimumSize(QSize(200, 0)) test_line.setObjectName( QString("test_line").append(QString(i))) test_line.setText(QString(param[2])) hlayout.addWidget(test_line) # If we have a dir_path or file_path add a select button if (paramName == QString('dir_path')) or (paramName == QString('file_path')): pbnSelect = QPushButton(widgetTemp) pbnSelect.setObjectName( QString('pbnSelect').append(QString(i))) pbnSelect.setText(QString("Select...")) pbnSelectDelegate = FileDialogSignal(typeName=paramName, param=test_line) QObject.connect( pbnSelectDelegate.o, SIGNAL("buttonPressed(PyQt_PyObject,PyQt_PyObject)"), self.on_pbnSelect_released) QObject.connect(pbnSelect, SIGNAL("released()"), pbnSelectDelegate.relayButtonSignal) self.test_line_delegates.append(pbnSelectDelegate) self.test_line_buttons.append(pbnSelect) hlayout.addWidget(pbnSelect) self.vboxlayout.addWidget(widgetTemp) self.adjustSize() # Jesse adding help text from opusHelp tool_path = self.optional_params.get('tool_path', '') try: exec_stmt = 'from %s.%s import opusHelp' % (tool_path, self.module_name) exec exec_stmt help = QString(opusHelp()) self.toolhelpEdit.insertPlainText(help) except Exception, e: help = 'could not find opusHelp function in tool module' self.toolhelpEdit.insertPlainText(help)
class OutputSwitcher(QFrame): """ The name is a bit misleading. This widget selectes sources for a specified destination. In mixer-usage this widget is at the top of the input-channel. Because the input of the mixer is an available output from the routers point. """ MixerRoutingChanged = pyqtSignal() def __init__(self, interface, outname, parent): QFrame.__init__(self, parent) self.interface = interface self.outname = outname self.lastin = "" self.setLineWidth(1) self.setFrameStyle(QFrame.Sunken | QFrame.Panel) self.layout = QGridLayout(self) self.setLayout(self.layout) self.lbl = QLabel(self.outname, self) self.lbl.setToolTip( "The name of the destination that is to be controlled here.") self.layout.addWidget(self.lbl, 0, 0) self.vu = VuMeter(self.interface, outname, parent=self) self.layout.addWidget(self.vu, 0, 1) sources = self.interface.getSourceNames() self.combo = QComboBox(self) self.combo.setToolTip( "<qt>Select the source for this destination.<br>Each destination can only receive sound from one source at a time. But one source can send sound to multiple destinations.</qt>" ) self.layout.addWidget(self.combo, 1, 0, 1, 2) self.combo.addItem("Disconnected") self.combo.addItems(sources) src = self.interface.getSourceForDestination(self.outname) self.lastin = str(src) if src != "": self.combo.setCurrentIndex(self.combo.findText(src)) else: self.combo.setCurrentIndex(0) self.combo.activated.connect(self.comboCurrentChanged) def peakValue(self, value): self.vu.updateLevel(value) pass def comboCurrentChanged(self, inname): #log.debug("comboCurrentChanged( %s )" % inname) if inname == self.lastin: return if self.lastin != "": self.interface.setConnectionState(self.lastin, self.outname, False) if inname != "Disconnected": if self.interface.setConnectionState(str(inname), self.outname, True): if self.outname[: 5] == "Mixer" or self.lastin[: 5] == "Mixer" or str( inname )[:5] == "Mixer": self.MixerRoutingChanged.emit() self.lastin = str(inname) else: log.warning(" Failed to connect %s to %s" % (inname, self.outname)) else: self.lastin = ""
class FindInFilesDialog(QDialog): def __init__(self, result_widget, parent): QDialog.__init__(self, parent) self._find_thread = FindInFilesThread() self.setWindowTitle("Find in files") self.resize(400, 300) #MAIN LAYOUT main_vbox = QVBoxLayout(self) self.pattern_line_edit = QLineEdit() self.dir_name_root = None self.user_home = os.path.expanduser('~') self.dir_combo = QComboBox() self.dir_combo.addItem(self.user_home) self.dir_combo.setEditable(True) self.open_button = QPushButton(QIcon(resources.IMAGES['find']), self.tr("Open")) self.filters_line_edit = QLineEdit("*.py") self.replace_line = QLineEdit() self.replace_line.setEnabled(False) self.check_replace = QCheckBox(self.tr("Replace: ")) self.case_checkbox = QCheckBox(self.tr("C&ase sensitive")) self.type_checkbox = QCheckBox(self.tr("R&egular Expression")) self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive")) self.recursive_checkbox.setCheckState(Qt.Checked) self.phrase_radio = QRadioButton( self.tr("Search by Phrase (Exact Match).")) self.phrase_radio.setChecked(True) self.words_radio = QRadioButton( self.tr("Search for all the words " "(anywhere in the document, not together).")) self.find_button = QPushButton(self.tr("Find!")) self.find_button.setMaximumWidth(150) self.cancel_button = QPushButton(self.tr("Cancel")) self.cancel_button.setMaximumWidth(150) self.result_widget = result_widget hbox = QHBoxLayout() hbox.addWidget(self.find_button) hbox.addWidget(self.cancel_button) #main section find_group_box = QGroupBox(self.tr("Main")) grid = QGridLayout() grid.addWidget(QLabel(self.tr("Text: ")), 0, 0) grid.addWidget(self.pattern_line_edit, 0, 1) grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0) grid.addWidget(self.dir_combo, 1, 1) grid.addWidget(self.open_button, 1, 2) grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0) grid.addWidget(self.filters_line_edit, 2, 1) grid.addWidget(self.check_replace, 3, 0) grid.addWidget(self.replace_line, 3, 1) find_group_box.setLayout(grid) #add main section to MAIN LAYOUT main_vbox.addWidget(find_group_box) #options sections options_group_box = QGroupBox(self.tr("Options")) gridOptions = QGridLayout() gridOptions.addWidget(self.case_checkbox, 0, 0) gridOptions.addWidget(self.type_checkbox, 1, 0) gridOptions.addWidget(self.recursive_checkbox, 2, 0) gridOptions.addWidget(self.phrase_radio, 0, 1) gridOptions.addWidget(self.words_radio, 1, 1) options_group_box.setLayout(gridOptions) #add options sections to MAIN LAYOUT main_vbox.addWidget(options_group_box) #add buttons to MAIN LAYOUT main_vbox.addLayout(hbox) #Focus self.pattern_line_edit.setFocus() self.open_button.setFocusPolicy(Qt.NoFocus) #signal self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir) self.connect(self.find_button, SIGNAL("clicked()"), self._find_in_files) self.connect(self.cancel_button, SIGNAL("clicked()"), self._kill_thread) self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"), self._found_match) self.connect(self._find_thread, SIGNAL("finished()"), self._find_thread_finished) self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"), self._change_radio_enabled) self.connect(self.check_replace, SIGNAL("stateChanged(int)"), self._replace_activated) self.connect(self.words_radio, SIGNAL("clicked(bool)"), self._words_radio_pressed) def _replace_activated(self): self.replace_line.setEnabled(self.check_replace.isChecked()) self.phrase_radio.setChecked(True) def _words_radio_pressed(self, value): self.replace_line.setEnabled(not value) self.check_replace.setChecked(not value) self.words_radio.setChecked(True) def _change_radio_enabled(self, val): enabled = not self.type_checkbox.isChecked() self.phrase_radio.setEnabled(enabled) self.words_radio.setEnabled(enabled) def show(self, actual_project=None, actual=None): self.dir_combo.clear() self.dir_name_root = actual_project if \ actual_project else [self.user_home] self.dir_combo.addItems(self.dir_name_root) if actual: index = self.dir_combo.findText(actual) self.dir_combo.setCurrentIndex(index) super(FindInFilesDialog, self).show() self.pattern_line_edit.setFocus() def reject(self): self._kill_thread() # Crazy hack to avoid circular imports self.result_widget.parent().parent().parent().hide() super(FindInFilesDialog, self).reject() def _find_thread_finished(self): self.emit(SIGNAL("finished()")) self._find_thread.wait() def _select_dir(self): dir_name = QFileDialog.getExistingDirectory(self, self.tr("Open Directory"), self.dir_combo.currentText(), QFileDialog.ShowDirsOnly) index = self.dir_combo.findText(dir_name) if index >= 0: self.dir_combo.setCurrentIndex(index) else: self.dir_combo.insertItem(0, dir_name) self.dir_combo.setCurrentIndex(0) def _found_match(self, result): file_name = result[0] items = result[1] self.result_widget.update_result( self.dir_combo.currentText(), file_name, items) def _kill_thread(self): if self._find_thread.isRunning(): self._find_thread.cancel() self.accept() def _find_in_files(self): self.emit(SIGNAL("findStarted()")) self._kill_thread() self.result_widget.clear() pattern = self.pattern_line_edit.text() dir_name = self.dir_combo.currentText() filters = re.split("[,;]", self.filters_line_edit.text()) # Version of PyQt API 1 # filters = self.filters_line_edit.text().split(QRegExp("[,;]"), # QString.SkipEmptyParts) #remove the spaces in the words Ex. (" *.foo"--> "*.foo") filters = [f.strip() for f in filters] case_sensitive = self.case_checkbox.isChecked() type_ = QRegExp.RegExp if \ self.type_checkbox.isChecked() else QRegExp.FixedString recursive = self.recursive_checkbox.isChecked() by_phrase = True if self.phrase_radio.isChecked() or self.type_checkbox.isChecked(): regExp = QRegExp(pattern, case_sensitive, type_) elif self.words_radio.isChecked(): by_phrase = False type_ = QRegExp.RegExp pattern = '|'.join( [word.strip() for word in pattern.split()]) regExp = QRegExp(pattern, case_sensitive, type_) #save a reference to the root directory where we find self.dir_name_root = dir_name self._find_thread.find_in_files(dir_name, filters, regExp, recursive, by_phrase)
class TreeLayerItem(QTreeWidgetItem): layerIcon = QIcon(os.path.join(os.path.dirname(__file__), "icons", "layer.png")) def __init__(self, iface, layer, tree, dlg): QTreeWidgetItem.__init__(self) self.iface = iface self.layer = layer self.setText(0, layer.name()) self.setIcon(0, self.layerIcon) project = QgsProject.instance() if project.layerTreeRoot().findLayer(layer.id()).isVisible(): self.setCheckState(0, Qt.Checked) else: self.setCheckState(0, Qt.Unchecked) self.visibleItem = QTreeWidgetItem(self) self.visibleCheck = QCheckBox() vis = layer.customProperty("qgis2web/Visible", True) if (vis == 0 or unicode(vis).lower() == "false"): self.visibleCheck.setChecked(False) else: self.visibleCheck.setChecked(True) self.visibleItem.setText(0, "Visible") self.addChild(self.visibleItem) tree.setItemWidget(self.visibleItem, 1, self.visibleCheck) if layer.type() == layer.VectorLayer: if layer.providerType() == 'WFS': self.jsonItem = QTreeWidgetItem(self) self.jsonCheck = QCheckBox() if layer.customProperty("qgis2web/Encode to JSON") == 2: self.jsonCheck.setChecked(True) self.jsonItem.setText(0, "Encode to JSON") self.jsonCheck.stateChanged.connect(self.changeJSON) self.addChild(self.jsonItem) tree.setItemWidget(self.jsonItem, 1, self.jsonCheck) if layer.geometryType() == QGis.Point: self.clusterItem = QTreeWidgetItem(self) self.clusterCheck = QCheckBox() if layer.customProperty("qgis2web/Cluster") == 2: self.clusterCheck.setChecked(True) self.clusterItem.setText(0, "Cluster") self.clusterCheck.stateChanged.connect(self.changeCluster) self.addChild(self.clusterItem) tree.setItemWidget(self.clusterItem, 1, self.clusterCheck) self.popupItem = QTreeWidgetItem(self) self.popupItem.setText(0, "Popup fields") options = [] fields = self.layer.pendingFields() for f in fields: fieldIndex = fields.indexFromName(unicode(f.name())) try: formCnf = layer.editFormConfig() editorWidget = formCnf.widgetType(fieldIndex) except: editorWidget = layer.editorWidgetV2(fieldIndex) if editorWidget == QgsVectorLayer.Hidden or \ editorWidget == 'Hidden': continue options.append(f.name()) for option in options: self.attr = QTreeWidgetItem(self) self.attrWidget = QComboBox() self.attrWidget.addItem("no label") self.attrWidget.addItem("inline label") self.attrWidget.addItem("header label") custProp = layer.customProperty("qgis2web/popup/" + option) if (custProp != "" and custProp is not None): self.attrWidget.setCurrentIndex( self.attrWidget.findText( layer.customProperty("qgis2web/popup/" + option))) self.attr.setText(1, option) self.popupItem.addChild(self.attr) tree.setItemWidget(self.attr, 2, self.attrWidget) self.addChild(self.popupItem) @property def popup(self): popup = [] self.tree = self.treeWidget() for p in xrange(self.childCount()): item = self.child(p).text(1) if item != "": popupVal = self.tree.itemWidget(self.child(p), 2).currentText() pair = (item, popupVal) popup.append(pair) popup = OrderedDict(popup) return popup @property def visible(self): return self.visibleCheck.isChecked() @property def json(self): try: return self.jsonCheck.isChecked() except: return False @property def cluster(self): try: return self.clusterCheck.isChecked() except: return False def changeJSON(self, isJSON): self.layer.setCustomProperty("qgis2web/Encode to JSON", isJSON) def changeCluster(self, isCluster): self.layer.setCustomProperty("qgis2web/Cluster", isCluster)
class GeneralSection(QWidget): def __init__(self): super(GeneralSection, self).__init__() container = QVBoxLayout(self) # Inicio group_on_start = QGroupBox(self.tr("Al Iniciar:")) box = QVBoxLayout(group_on_start) box.setContentsMargins(20, 5, 20, 5) self.check_splash = QCheckBox(self.tr("Mostrar Splash")) self.check_splash.setChecked( settings.get_setting('general/show-splash')) box.addWidget(self.check_splash) self.check_on_start = QCheckBox(self.tr("Mostrar Página de Inicio")) show_start_page = settings.get_setting('general/show-start-page') self.check_on_start.setChecked(show_start_page) box.addWidget(self.check_on_start) self.check_load_files = QCheckBox(self.tr("Cargar archivos desde la " "última sesión")) load_files = settings.get_setting('general/load-files') self.check_load_files.setChecked(load_files) box.addWidget(self.check_load_files) container.addWidget(group_on_start) # Al salir group_on_exit = QGroupBox(self.tr("Al Salir:")) box = QVBoxLayout(group_on_exit) box.setContentsMargins(20, 5, 20, 5) self.check_on_exit = QCheckBox(self.tr("Confirmar Salida")) self.check_on_exit.setChecked( settings.get_setting('general/confirm-exit')) box.addWidget(self.check_on_exit) self.check_geometry = QCheckBox(self.tr( "Guardar posición y tamaño de la ventana")) self.check_geometry.setChecked( settings.get_setting('window/store-size')) box.addWidget(self.check_geometry) container.addWidget(group_on_exit) # Notificaciones group_notifications = QGroupBox(self.tr("Notificaciones:")) box = QVBoxLayout(group_notifications) box.setContentsMargins(20, 5, 20, 5) self.check_updates = QCheckBox(self.tr("Buscar Actualizaciones")) self.check_updates.setChecked( settings.get_setting('general/check-updates')) box.addWidget(self.check_updates) container.addWidget(group_notifications) # Sistema if settings.IS_LINUX: group_terminal = QGroupBox(self.tr("Sistema:")) box = QHBoxLayout(group_terminal) box.addWidget(QLabel(self.tr("Ejecutar programa con:"))) self.line_terminal = QLineEdit() self.line_terminal.setAlignment(Qt.AlignLeft) self.line_terminal.setFixedWidth(300) self.line_terminal.setText(settings.get_setting('terminal')) box.addWidget(self.line_terminal, 1, Qt.AlignLeft) container.addWidget(group_terminal) # User Interface group_ui = QGroupBox(self.tr("Interfáz de Usuario:")) box = QGridLayout(group_ui) box.setContentsMargins(20, 5, 20, 5) box.addWidget(QLabel(self.tr("Tema:")), 0, 0) self.combo_theme = QComboBox() self.combo_theme.setFixedWidth(200) self._update_combo() index = self.combo_theme.findText( settings.get_setting('window/style-sheet')) self.combo_theme.setCurrentIndex(index) box.addWidget(self.combo_theme, 0, 1) self.combo_lang = QComboBox() self.combo_lang.setFixedWidth(200) box.addWidget(QLabel(self.tr("Idioma:")), 1, 0) box.addWidget(self.combo_lang, 1, 1) langs = os.listdir(os.path.join(paths.PATH, "extras", "i18n")) self.combo_lang.addItems(["Spanish"] + [lang[:-3] for lang in langs]) lang = settings.get_setting('general/language') index = 0 if not lang else self.combo_lang.findText(lang) self.combo_lang.setCurrentIndex(index) container.addWidget(group_ui) box.setAlignment(Qt.AlignLeft) # Reestablecer group_restart = QGroupBox(self.tr("Reestablecer:")) box = QHBoxLayout(group_restart) box.setContentsMargins(20, 5, 20, 5) btn_restart = QPushButton(self.tr("Reiniciar configuraciones")) btn_restart.setObjectName("custom") box.addWidget(btn_restart) box.addStretch(1) container.addWidget(group_restart) container.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding)) # Conexiones btn_restart.clicked.connect(self._restart_configurations) self.combo_theme.currentIndexChanged[int].connect( self._change_style_sheet) # Install EnvironmentConfiguration.install_widget(self.tr("General"), self) def _update_combo(self): self.combo_theme.addItems(['Default', 'Edark']) list_dir = os.listdir(paths.EDIS) list_styles = [i.split('.')[0]for i in list_dir if os.path.splitext(i)[-1] == '.qss'] self.combo_theme.insertItems(2, list_styles) def _change_style_sheet(self, index): style_sheet = None path = None if index == 1: path = os.path.join(paths.PATH, "extras", "theme", "edark.qss") elif index != 0: style = self.combo_styles.currentText() + '.qss' path = os.path.join(paths.EDIS, style) if path is not None: with open(path, mode='r') as f: style_sheet = f.read() QApplication.instance().setStyleSheet(style_sheet) def _restart_configurations(self): flags = QMessageBox.Cancel flags |= QMessageBox.Yes result = QMessageBox.question(self, self.tr("Advertencia!"), self.tr("Está seguro que quiere " "reestablecer las " "configuraciones?"), flags) if result == QMessageBox.Cancel: return elif result == QMessageBox.Yes: QSettings(paths.CONFIGURACION, QSettings.IniFormat).clear() dialog_preferences = Edis.get_component("preferences") dialog_preferences.close() def save(self): settings.set_setting('general/show-splash', self.check_splash.isChecked()) show_start_page = self.check_on_start.isChecked() settings.set_setting('general/show-start-page', show_start_page) settings.set_setting('ventana/store-size', self.check_geometry.isChecked()) settings.set_setting('general/confirm-exit', self.check_on_exit.isChecked()) settings.set_setting('general/check-updates', self.check_updates.isChecked()) load_files = self.check_load_files.isChecked() settings.set_setting('general/load-files', load_files) lang = self.combo_lang.currentText() settings.set_setting('general/language', lang) if settings.IS_LINUX: settings.set_setting('terminal', self.line_terminal.text())
class TreeSettingItem(QTreeWidgetItem): def __init__(self, parent, tree, name, value, action=None): QTreeWidgetItem.__init__(self, parent) self.parent = parent self.tree = tree self.name = name self._value = value self.combo = None self.setText(0, name) widget = None if isinstance(value, bool): if value: self.setCheckState(1, Qt.Checked) else: self.setCheckState(1, Qt.Unchecked) elif isinstance(value, tuple): self.combo = QComboBox() self.combo.setSizeAdjustPolicy(0) for option in value: self.combo.addItem(option) widget = self.combo else: self.setText(1, unicode(value)) if action: layout = QHBoxLayout() layout.setMargin(0) if widget: layout.addWidget(widget) button = QToolButton() button.setDefaultAction(action) button.setText(action.text()) layout.addWidget(button) layout.addStretch(1) widget = QWidget() widget.setLayout(layout) if widget: self.tree.setItemWidget(self, 1, widget) def setValue(self, value): if isinstance(value, bool): if value: self.setCheckState(1, Qt.Checked) else: self.setCheckState(1, Qt.Unchecked) elif self.combo: index = self.combo.findText(value) if index != -1: self.combo.setCurrentIndex(index) else: self.setText(1, unicode(value)) def value(self): if isinstance(self._value, bool): return self.checkState(1) == Qt.Checked elif isinstance(self._value, (int, float)): return float(self.text(1)) elif isinstance(self._value, tuple): return self.combo.currentText() else: return self.text(1)