本文整理汇总了Python中qgis.PyQt.QtCore.QSettings类的典型用法代码示例。如果您正苦于以下问题:Python QSettings类的具体用法?Python QSettings怎么用?Python QSettings使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QSettings类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getVectorWriter
def getVectorWriter(self, fields, geomType, crs, options=None):
"""Returns a suitable writer to which features can be added as
a result of the algorithm. Use this to transparently handle
output values instead of creating your own method.
Executing this method might modify the object, adding additional
information to it, so the writer can be later accessed and
processed within QGIS. It should be called just once, since a
new call might result in previous data being replaced, thus
rendering a previously obtained writer useless.
@param fields a list of QgsField
@param geomType a suitable geometry type, as it would be passed
to a QgsVectorFileWriter constructor
@param crs the crs of the layer to create
@return writer instance of the vector writer class
"""
if self.encoding is None:
settings = QSettings()
self.encoding = settings.value('/Processing/encoding', 'System', str)
w = VectorWriter(self.value, self.encoding, fields, geomType,
crs, options)
self.layer = w.layer
self.value = w.destination
return w
示例2: canvasReleaseEvent
def canvasReleaseEvent(self, e):
point = self.plugin.transform(
self.iface.mapCanvas().getCoordinateTransform().toMapCoordinates(e.x(), e.y())
)
QApplication.setOverrideCursor(Qt.WaitCursor)
fs = self.plugin.highlight(
where=u"st_contains(wkb_geometry,st_geomfromtext('POINT(%.3lf %.3lf)'::text,%d))" % (
point.x(), point.y(), self.plugin.getepsg()
)
)
if len(fs) == 0:
QApplication.restoreOverrideCursor()
QMessageBox.information(None, u"Fehler", u"Kein Flurstück gefunden.")
return
try:
s = QSettings("norBIT", "EDBSgen/PRO")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("localhost", int(s.value("norGISPort", "6102"))))
sock.send("NORGIS_MAIN#EDBS#ALBKEY#{}#".format(fs[0]['flsnr']).encode("utf-8"))
sock.close()
if win32:
window = win32gui.FindWindow(None, s.value("albWin", "norGIS"))
win32gui.SetForegroundWindow(window)
except socket.error:
QMessageBox.information(None, u"Fehler", u"Verbindung zu norGIS schlug fehl.")
QApplication.restoreOverrideCursor()
示例3: showFileSelectionDialog
def showFileSelectionDialog(self):
settings = QSettings()
text = str(self.text.text())
if os.path.isdir(text):
path = text
elif os.path.isdir(os.path.dirname(text)):
path = os.path.dirname(text)
elif settings.contains('/Processing/LastInputPath'):
path = str(settings.value('/Processing/LastInputPath'))
else:
path = ''
ret, selected_filter = QFileDialog.getOpenFileNames(self, self.tr('Open file'), path,
self.tr('All files(*.*);;') + self.param.getFileFilter())
if ret:
files = list(ret)
settings.setValue('/Processing/LastInputPath',
os.path.dirname(str(files[0])))
for i, filename in enumerate(files):
files[i] = dataobjects.getRasterSublayer(filename, self.param)
if len(files) == 1:
self.text.setText(files[0])
self.textEditingFinished()
else:
if isinstance(self.param, ParameterMultipleInput):
self.text.setText(';'.join(str(f) for f in files))
else:
rowdif = len(files) - (self._table().rowCount() - self.row)
for i in range(rowdif):
self._panel().addRow()
for i, f in enumerate(files):
self._table().cellWidget(i + self.row,
self.col).setValue(f)
示例4: initGui
def initGui(self):
layout = QVBoxLayout()
self.tab = QTabWidget()
self.table = QTableView()
self.setLayout(layout)
self.canvas = QgsMapCanvas()
self.canvas.setCanvasColor(Qt.white)
settings = QSettings()
self.canvas.enableAntiAliasing(settings.value("/qgis/enable_anti_aliasing", False, type = bool))
self.canvas.useImageToRender(settings.value("/qgis/use_qimage_to_render", False, type = bool))
self.canvas.mapSettings().setDestinationCrs(self.crs)
action = settings.value("/qgis/wheel_action", 0, type = float)
zoomFactor = settings.value("/qgis/zoom_factor", 2, type = float)
self.canvas.setWheelAction(QgsMapCanvas.WheelAction(action), zoomFactor)
self.panTool = QgsMapToolPan(self.canvas)
self.canvas.setMapTool(self.panTool)
execute(self.createLayers)
model = GeomDiffTableModel(self.data)
self.table.setModel(model)
self.table.resizeColumnsToContents()
self.table.resizeRowsToContents()
self.tab.addTab(self.canvas, "Map view")
self.tab.addTab(self.table, "Table view")
layout.addWidget(self.tab)
self.resize(600, 500)
self.setWindowTitle("Geometry comparison")
示例5: main
def main():
datestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
if QT5:
ini_out_dir = QStandardPaths.writableLocation(QStandardPaths.DesktopLocation)
else:
ini_out_dir = QDesktopServices.storageLocation(QDesktopServices.DesktopLocation)
ini_name = 'org.qgis.{0}-settings_{1}.ini'.format(QGIS_APP_NAME, datestamp)
ini_out = QDir(ini_out_dir).absoluteFilePath(ini_name)
if not os.path.exists(ini_out_dir):
print('INI output directory does not exist: {0}'.format(ini_out_dir))
return
if not os.access(ini_out_dir, os.W_OK | os.X_OK):
print('INI output directory is not writeable: {0}'.format(ini_out_dir))
return
# QGIS settings
if HAS_QGSSETTINGS:
qgis_settings = QgsSettings()
else:
qgis_settings = QSettings()
# Output INI settings
ini_settings = QSettings(ini_out, QSettings.IniFormat)
qgis_keys = qgis_settings.allKeys()
for k in qgis_keys:
ini_settings.setValue(k, qgis_settings.value(k))
ini_settings.sync()
print("Settings output to: {0}".format(QDir.toNativeSeparators(ini_out)))
示例6: export
def export(self):
""" Export the results to a CSV file """
# Remember the last location in which we saved
settings = QSettings()
lastFolder = str(settings.value("constraintchecker/lastSaveFolder", os.sep))
outFileName, ext_selector = QFileDialog.getSaveFileName(self, 'Save Query Results', lastFolder,
'Comma Separated Variable Files (*.csv)')
# Store the path we just looked in
head, tail = os.path.split(outFileName)
if head != os.sep and head.lower() != 'c:\\' and head != '':
settings.setValue("constraintchecker/lastSaveFolder", head)
if len(outFileName) == 0:
# User hit cancel
return
# Export the file
try:
csvfile = open(outFileName+'.csv', 'w')
except:
msg = 'Failed to open %s for writing - perhaps it is open in another application?' % outFileName
QMessageBox.critical(self, 'Failed to Open File', msg)
return
resWriter = csv.writer(csvfile)
resWriter.writerow(self.resultModel.headerNames)
for i in range(self.resultModel.rowCount()):
resWriter.writerow(self.resultModel.fetchRow(i))
csvfile.close()
示例7: load_directories
def load_directories(self):
"""Load directories of repository registered in settings."""
self._directories = {}
settings = QSettings()
settings.beginGroup(repo_settings_group())
# Write online directory first to QSettings if needed
for online_dir_name in self._online_directories:
repo_present = False
for repo_name in settings.childGroups():
url = settings.value(repo_name + '/url', '', type=unicode)
if url == self._online_directories[online_dir_name]:
repo_present = True
break
if not repo_present:
self.add_directory(
online_dir_name, self._online_directories[online_dir_name])
for repo_name in settings.childGroups():
self._directories[repo_name] = {}
url = settings.value(
repo_name + '/url', '', type=unicode)
self._directories[repo_name]['url'] = url
auth_cfg = settings.value(
repo_name + '/auth_cfg', '', type=unicode).strip()
self._directories[repo_name]['auth_cfg'] = auth_cfg
settings.endGroup()
示例8: execute
def execute(self):
settings = QSettings()
lastDir = settings.value('Processing/lastModelsDir', '')
filename, selected_filter = QFileDialog.getOpenFileName(self.toolbox,
self.tr('Open model', 'AddModelFromFileAction'), lastDir,
self.tr('Processing model files (*.model *.MODEL)', 'AddModelFromFileAction'))
if filename:
try:
settings.setValue('Processing/lastModelsDir',
QFileInfo(filename).absoluteDir().absolutePath())
ModelerAlgorithm.fromFile(filename)
except WrongModelException:
QMessageBox.warning(
self.toolbox,
self.tr('Error reading model', 'AddModelFromFileAction'),
self.tr('The selected file does not contain a valid model', 'AddModelFromFileAction'))
return
except:
QMessageBox.warning(self.toolbox,
self.tr('Error reading model', 'AddModelFromFileAction'),
self.tr('Cannot read file', 'AddModelFromFileAction'))
return
destFilename = os.path.join(ModelerUtils.modelsFolders()[0], os.path.basename(filename))
shutil.copyfile(filename, destFilename)
algList.reloadProvider('model')
示例9: processAlgorithm
def processAlgorithm(self, progress):
connection = self.getParameterValue(self.DATABASE)
settings = QSettings()
mySettings = '/PostgreSQL/connections/' + connection
try:
database = settings.value(mySettings + '/database')
username = settings.value(mySettings + '/username')
host = settings.value(mySettings + '/host')
port = settings.value(mySettings + '/port', type=int)
password = settings.value(mySettings + '/password')
except Exception as e:
raise GeoAlgorithmExecutionException(
self.tr('Wrong database connection name: %s' % connection))
try:
self.db = postgis_utils.GeoDB(host=host, port=port,
dbname=database, user=username, passwd=password)
except postgis_utils.DbError as e:
raise GeoAlgorithmExecutionException(
self.tr("Couldn't connect to database:\n%s") % unicode(e))
sql = self.getParameterValue(self.SQL).replace('\n', ' ')
try:
self.db._exec_sql_and_commit(unicode(sql))
except postgis_utils.DbError as e:
raise GeoAlgorithmExecutionException(
self.tr('Error executing SQL:\n%s') % unicode(e))
示例10: processAlgorithm
def processAlgorithm(self, progress):
"""Here is where the processing itself takes place."""
# The first thing to do is retrieve the values of the parameters
# entered by the user
inputFilename = self.getParameterValue(self.INPUT_LAYER)
output = self.getOutputValue(self.OUTPUT_LAYER)
# Input layers vales are always a string with its location.
# That string can be converted into a QGIS object (a
# QgsVectorLayer in this case) using the
# processing.getObjectFromUri() method.
vectorLayer = dataobjects.getObjectFromUri(inputFilename)
# And now we can process
# First we create the output layer. The output value entered by
# the user is a string containing a filename, so we can use it
# directly
settings = QSettings()
systemEncoding = settings.value('/UI/encoding', 'System')
writer = QgsVectorFileWriter(output,
systemEncoding,
vectorLayer.fields(),
vectorLayer.wkbType(),
vectorLayer.crs())
# Now we take the features from input layer and add them to the
# output. Method features() returns an iterator, considering the
# selection that might exist in layer and the configuration that
# indicates should algorithm use only selected features or all
# of them
features = vector.features(vectorLayer)
for f in features:
writer.addFeature(f)
示例11: read
def read(self):
qsettings = QSettings()
value = qsettings.value(self.qname, None)
if value is not None:
if isinstance(self.value, bool):
value = str(value).lower() == str(True).lower()
self.value = value
示例12: showSelectionDialog
def showSelectionDialog(self):
if isinstance(self.output, OutputDirectory):
self.selectDirectory()
return
filefilter = self.output.getFileFilter(self.alg)
settings = QSettings()
if settings.contains('/Processing/LastBatchOutputPath'):
path = str(settings.value('/Processing/LastBatchOutputPath'))
else:
path = ''
filename, selectedFileFilter = QFileDialog.getSaveFileName(self,
self.tr('Save file'), path, filefilter)
if filename:
if not filename.lower().endswith(
tuple(re.findall("\*(\.[a-z]{1,10})", filefilter))):
ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter)
if ext:
filename += ext.group(1)
settings.setValue('/Processing/LastBatchOutputPath', os.path.dirname(filename))
dlg = AutofillDialog(self.alg)
dlg.exec_()
if dlg.mode is not None:
try:
if dlg.mode == AutofillDialog.DO_NOT_AUTOFILL:
self.table.cellWidget(self.row,
self.col).setValue(filename)
elif dlg.mode == AutofillDialog.FILL_WITH_NUMBERS:
n = self.table.rowCount() - self.row
for i in range(n):
name = filename[:filename.rfind('.')] \
+ str(i + 1) + filename[filename.rfind('.'):]
self.table.cellWidget(i + self.row,
self.col).setValue(name)
elif dlg.mode == AutofillDialog.FILL_WITH_PARAMETER:
n = self.table.rowCount() - self.row
for i in range(n):
widget = self.table.cellWidget(i + self.row,
dlg.param)
param = self.alg.parameters[dlg.param]
if isinstance(param, (ParameterRaster,
ParameterVector, ParameterTable,
ParameterMultipleInput)):
s = str(widget.getText())
s = os.path.basename(s)
s = os.path.splitext(s)[0]
elif isinstance(param, ParameterBoolean):
s = str(widget.currentIndex() == 0)
elif isinstance(param, ParameterSelection):
s = str(widget.currentText())
elif isinstance(param, ParameterFixedTable):
s = str(widget.table)
else:
s = str(widget.text())
name = filename[:filename.rfind('.')] + s \
+ filename[filename.rfind('.'):]
self.table.cellWidget(i + self.row,
self.col).setValue(name)
except:
pass
示例13: chooseOutputFile
def chooseOutputFile(self):
# get last used dir
settings = QSettings()
lastUsedDir = settings.value(self.lastUsedVectorDirSettingsKey, ".")
# get selected filter
selectedFilter = self.cboFileFormat.itemData(self.cboFileFormat.currentIndex())
# ask for a filename
filename, filter = QFileDialog.getSaveFileName(self, self.tr("Choose where to save the file"), lastUsedDir,
selectedFilter)
if filename == "":
return
filterString = QgsVectorFileWriter.filterForDriver(selectedFilter)
ext = filterString[filterString.find('.'):]
ext = ext[:ext.find(' ')]
if not filename.lower().endswith(ext):
filename += ext
# store the last used dir
settings.setValue(self.lastUsedVectorDirSettingsKey, QFileInfo(filename).filePath())
self.editOutputFile.setText(filename)
示例14: __init__
def __init__(self, repo, path):
super(VersionViewerDialog, self).__init__(config.iface.mainWindow(), Qt.WindowSystemMenuHint | Qt.WindowTitleHint)
self.repo = repo
self.path = path
self.setupUi(self)
self.listWidget.itemClicked.connect(self.commitClicked)
settings = QSettings()
horizontalLayout = QHBoxLayout()
horizontalLayout.setSpacing(0)
horizontalLayout.setMargin(0)
self.mapCanvas = QgsMapCanvas()
self.mapCanvas.setCanvasColor(Qt.white)
self.mapCanvas.enableAntiAliasing(settings.value("/qgis/enable_anti_aliasing", False, type = bool))
self.mapCanvas.useImageToRender(settings.value("/qgis/use_qimage_to_render", False, type = bool))
action = settings.value("/qgis/wheel_action", 0, type = float)
zoomFactor = settings.value("/qgis/zoom_factor", 2, type = float)
self.mapCanvas.setWheelAction(QgsMapCanvas.WheelAction(action), zoomFactor)
horizontalLayout.addWidget(self.mapCanvas)
self.mapWidget.setLayout(horizontalLayout)
self.panTool = QgsMapToolPan(self.mapCanvas)
self.mapCanvas.setMapTool(self.panTool)
versions = repo.log(path = path)
if versions:
for commit in versions:
item = CommitListItem(commit, repo, path)
self.listWidget.addItem(item)
''''w = CommitListItemWidget(commit)
self.ui.listWidget.setItemWidget(item, w)'''
else:
raise GeoGigException("The selected feature is not versioned yet")
示例15: qgisLocale
def qgisLocale():
settings = QSettings();
overrideLocale = settings.value("locale/overrideFlag", False, bool)
if overrideLocale:
return settings.value("locale/userLocale", "")
else:
return QLocale.system().name()[:2]