81 changes: 37 additions & 44 deletions python/console/console_editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,9 @@ def __init__(self, parent=None):
def settingsEditor(self):
# Set Python lexer
self.setLexers()
threshold = self.settings.value("pythonConsole/autoCompThresholdEditor", 2).toInt()[0]
radioButtonSource = self.settings.value("pythonConsole/autoCompleteSourceEditor", 'fromAPI').toString()
autoCompEnabled = self.settings.value("pythonConsole/autoCompleteEnabledEditor", True).toBool()
threshold = self.settings.value("pythonConsole/autoCompThresholdEditor", 2, type=int)
radioButtonSource = self.settings.value("pythonConsole/autoCompleteSourceEditor", 'fromAPI')
autoCompEnabled = self.settings.value("pythonConsole/autoCompleteEnabledEditor", True)
self.setAutoCompletionThreshold(threshold)
if autoCompEnabled:
if radioButtonSource == 'fromDoc':
Expand All @@ -198,8 +198,8 @@ def settingsEditor(self):
self.setAutoCompletionSource(self.AcsNone)

def autoCompleteKeyBinding(self):
radioButtonSource = self.settings.value("pythonConsole/autoCompleteSourceEditor").toString()
autoCompEnabled = self.settings.value("pythonConsole/autoCompleteEnabledEditor").toBool()
radioButtonSource = self.settings.value("pythonConsole/autoCompleteSourceEditor")
autoCompEnabled = self.settings.value("pythonConsole/autoCompleteEnabledEditor")
if autoCompEnabled:
if radioButtonSource == 'fromDoc':
self.autoCompleteFromDocument()
Expand All @@ -216,8 +216,8 @@ def setLexers(self):
self.lexer.setFoldComments(True)
self.lexer.setFoldQuotes(True)

loadFont = self.settings.value("pythonConsole/fontfamilytextEditor", "Monospace").toString()
fontSize = self.settings.value("pythonConsole/fontsizeEditor", 10).toInt()[0]
loadFont = self.settings.value("pythonConsole/fontfamilytextEditor", "Monospace")
fontSize = self.settings.value("pythonConsole/fontsizeEditor", 10, type=int)

font = QFont(loadFont)
font.setFixedPitch(True)
Expand All @@ -236,11 +236,11 @@ def setLexers(self):
self.lexer.setFont(font, 4)

self.api = QsciAPIs(self.lexer)
chekBoxAPI = self.settings.value("pythonConsole/preloadAPI", True).toBool()
chekBoxAPI = self.settings.value("pythonConsole/preloadAPI", True)
if chekBoxAPI:
self.api.loadPrepared( QgsApplication.pkgDataPath() + "/python/qsci_apis/pyqgis_master.pap" )
else:
apiPath = self.settings.value("pythonConsole/userAPI").toStringList()
apiPath = self.settings.value("pythonConsole/userAPI")
for i in range(0, len(apiPath)):
self.api.load(QString(unicode(apiPath[i])))
self.api.prepare()
Expand All @@ -258,7 +258,7 @@ def move_cursor_to_end(self):
def get_end_pos(self):
"""Return (line, index) position of the last character"""
line = self.lines() - 1
return (line, self.text(line).length())
return (line, len(self.text(line)))

def contextMenuEvent(self, e):
menu = QMenu(self)
Expand Down Expand Up @@ -372,7 +372,7 @@ def contextMenuEvent(self, e):
if QApplication.clipboard().text():
pasteAction.setEnabled(True)
if self.settings.value("pythonConsole/enableObjectInsp",
False).toBool():
False):
showCodeInspection.setEnabled(True)
action = menu.exec_(self.mapToGlobal(e.pos()))

Expand All @@ -385,7 +385,7 @@ def findText(self, forward):
cs = self.parent.pc.caseSensitive.isChecked()
wo = self.parent.pc.wholeWord.isChecked()
notFound = False
if not text.isEmpty():
if text:
if not forward:
line = lineFrom
index = indexFrom
Expand All @@ -397,7 +397,7 @@ def findText(self, forward):
styleError = 'QLineEdit {background-color: #d65253; \
color: #ffffff;}'
msgText = QCoreApplication.translate('PythonConsole',
'<b>"%1"</b> was not found.').arg(text)
'<b>"{}"</b> was not found.'.format(text))
self.parent.pc.callWidgetMessageBarEditor(msgText, 0, True)
else:
styleError = ''
Expand Down Expand Up @@ -462,7 +462,7 @@ def commentEditorCode(self, commentCheck):
if commentCheck:
self.insertAt('#', line, 0)
else:
if not self.text(line).trimmed().startsWith('#'):
if not self.text(line).strip().startswith('#'):
continue
self.setSelection(line, self.indentation(line),
line, self.indentation(line) + 1)
Expand All @@ -472,7 +472,7 @@ def commentEditorCode(self, commentCheck):
if commentCheck:
self.insertAt('#', line, 0)
else:
if not self.text(line).trimmed().startsWith('#'):
if not self.text(line).strip().startswith('#'):
return
self.setSelection(line, self.indentation(line),
line, self.indentation(line) + 1)
Expand Down Expand Up @@ -519,17 +519,17 @@ def _runSubProcess(self, filename, tmp=False):
else:
raise e
if tmp:
tmpFileTr = QCoreApplication.translate('PythonConsole', ' [Temporary file saved in %1]').arg(dir)
tmpFileTr = QCoreApplication.translate('PythonConsole', ' [Temporary file saved in {}]'.format(dir))
file = file + tmpFileTr
if _traceback:
msgTraceTr = QCoreApplication.translate('PythonConsole', '## Script error: %1').arg(file)
msgTraceTr = QCoreApplication.translate('PythonConsole', '## Script error: {}'.format(file))
print "## %s" % datetime.datetime.now()
print unicode(msgTraceTr)
sys.stderr.write(_traceback)
p.stderr.close()
else:
msgSuccessTr = QCoreApplication.translate('PythonConsole',
'## Script executed successfully: %1').arg(file)
'## Script executed successfully: {}'.format(file))
print "## %s" % datetime.datetime.now()
print unicode(msgSuccessTr)
sys.stdout.write(out)
Expand All @@ -539,16 +539,15 @@ def _runSubProcess(self, filename, tmp=False):
os.remove(filename)
except IOError, error:
IOErrorTr = QCoreApplication.translate('PythonConsole',
'Cannot execute file %1. Error: %2\n') \
.arg(unicode(filename)).arg(error.strerror)
'Cannot execute file {}. Error: {}\n'.format(unicode(filename), error.strerror))
print '## Error: ' + IOErrorTr
except:
s = traceback.format_exc()
print '## Error: '
sys.stderr.write(s)

def runScriptCode(self):
autoSave = self.settings.value("pythonConsole/autoSaveScript").toBool()
autoSave = self.settings.value("pythonConsole/autoSaveScript")

tabWidget = self.parent.tw.currentWidget()

Expand Down Expand Up @@ -625,7 +624,7 @@ def syntaxCheck(self, filename=None, fromContextMenu=True):
self.bufferMarkerLine.append(eline)
self.markerAdd(eline, self.MARKER_NUM)
loadFont = self.settings.value("pythonConsole/fontfamilytextEditor",
"Monospace").toString()
"Monospace")
styleAnn = QsciStyle(-1,"Annotation",
QColor(255,0,0),
QColor(255,200,0),
Expand All @@ -646,7 +645,7 @@ def syntaxCheck(self, filename=None, fromContextMenu=True):
return True

def keyPressEvent(self, e):
if self.settings.value("pythonConsole/autoCloseBracketEditor", True).toBool():
if self.settings.value("pythonConsole/autoCloseBracketEditor", True):
t = unicode(e.text())
## Close bracket automatically
if t in self.opening:
Expand All @@ -659,8 +658,7 @@ def focusInEvent(self, e):
if pathfile:
if not QFileInfo(pathfile).exists():
msgText = QCoreApplication.translate('PythonConsole',
'The file <b>"%1"</b> has been deleted or is not accessible') \
.arg(unicode(pathfile))
'The file <b>"{}"</b> has been deleted or is not accessible'.format(unicode(pathfile)))
self.parent.pc.callWidgetMessageBarEditor(msgText, 2, False)
return
if pathfile and self.lastModified != QFileInfo(pathfile).lastModified():
Expand All @@ -681,16 +679,14 @@ def focusInEvent(self, e):
self.parent.tw.listObject(self.parent.tw.currentWidget())
self.lastModified = QFileInfo(pathfile).lastModified()
msgText = QCoreApplication.translate('PythonConsole',
'The file <b>"%1"</b> has been changed and reloaded') \
.arg(unicode(pathfile))
'The file <b>"{}"</b> has been changed and reloaded'.format(unicode(pathfile)))
self.parent.pc.callWidgetMessageBarEditor(msgText, 1, False)
QsciScintilla.focusInEvent(self, e)

def fileReadOnly(self):
tabWidget = self.parent.tw.currentWidget()
msgText = QCoreApplication.translate('PythonConsole',
'The file <b>"%1"</b> is read only, please save to different file first.') \
.arg(unicode(tabWidget.path))
'The file <b>"{}"</b> is read only, please save to different file first.'.format(unicode(tabWidget.path)))
self.parent.pc.callWidgetMessageBarEditor(msgText, 1, False)

class EditorTab(QWidget):
Expand Down Expand Up @@ -860,7 +856,7 @@ def __init__(self, parent):
# Restore script of the previuos session
self.settings = QSettings()
tabScripts = self.settings.value("pythonConsole/tabScripts")
self.restoreTabList = tabScripts.toList()
self.restoreTabList = tabScripts

if self.restoreTabList:
self.topFrame.show()
Expand Down Expand Up @@ -907,7 +903,7 @@ def __init__(self, parent):

def _currentWidgetChanged(self, tab):
if self.settings.value("pythonConsole/enableObjectInsp",
False).toBool():
False, type=bool):
self.listObject(tab)
self.changeLastDirPath(tab)
self.enableSaveIfModified(tab)
Expand Down Expand Up @@ -983,15 +979,14 @@ def newTabEditor(self, tabName=None, filename=None):
fn.close()
except IOError, error:
IOErrorTr = QCoreApplication.translate('PythonConsole',
'The file %1 could not be opened. Error: %2\n') \
.arg(unicode(filename)).arg(error.strerror)
'The file {} could not be opened. Error: {}\n'.format(unicode(filename), error.strerror))
print '## Error: '
sys.stderr.write(IOErrorTr)
return

nr = self.count()
if not tabName:
tabName = QCoreApplication.translate('PythonConsole', 'Untitled-%1').arg(nr)
tabName = QCoreApplication.translate('PythonConsole', 'Untitled-{}'.format(nr))
self.tab = EditorTab(self, self.parent, filename, readOnly)
self.iconTab = QgsApplication.getThemeIcon('console/iconTabEditorConsole.png')
self.addTab(self.tab, self.iconTab, tabName + ' (ro)' if readOnly else tabName)
Expand Down Expand Up @@ -1026,8 +1021,7 @@ def _removeTab(self, tab, tab2index=False):
txtSaveOnRemove = QCoreApplication.translate("PythonConsole",
"Python Console: Save File")
txtMsgSaveOnRemove = QCoreApplication.translate("PythonConsole",
"The file <b>'%1'</b> has been modified, save changes?") \
.arg(self.tabText(tab))
"The file <b>'{}'</b> has been modified, save changes?".format(self.tabText(tab)))
res = QMessageBox.question( self, txtSaveOnRemove,
txtMsgSaveOnRemove,
QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel )
Expand Down Expand Up @@ -1065,14 +1059,13 @@ def closeCurrentWidget(self):

def restoreTabs(self):
for script in self.restoreTabList:
pathFile = unicode(script.toString())
pathFile = unicode(script)
if QFileInfo(pathFile).exists():
tabName = pathFile.split('/')[-1]
self.newTabEditor(tabName, pathFile)
else:
errOnRestore = QCoreApplication.translate("PythonConsole",
"Unable to restore the file: \n%1\n") \
.arg(unicode(pathFile))
"Unable to restore the file: \n{}\n".format(unicode(pathFile)))
print '## Error: '
s = errOnRestore
sys.stderr.write(s)
Expand All @@ -1093,11 +1086,11 @@ def showFileTabMenu(self):
self.fileTabMenu.clear()
for index in range(self.count()):
action = self.fileTabMenu.addAction(self.tabIcon(index), self.tabText(index))
action.setData(QVariant(index))
action.setData(index)

def showFileTabMenuTriggered(self, action):
index, ok = action.data().toInt()
if ok:
index = action.data()
if index is not None:
self.setCurrentIndex(index)

def listObject(self, tab):
Expand Down Expand Up @@ -1188,7 +1181,7 @@ def refreshSettingsEditor(self):
self.widget(i).newEditor.settingsEditor()

objInspectorEnabled = self.settings.value("pythonConsole/enableObjectInsp",
False).toBool()
False, type=bool)
listObj = self.parent.objectListButton
if self.parent.listClassMethod.isVisible():
listObj.setChecked(objInspectorEnabled)
Expand All @@ -1203,7 +1196,7 @@ def refreshSettingsEditor(self):
def changeLastDirPath(self, tab):
tabWidget = self.widget(tab)
if tabWidget:
self.settings.setValue("pythonConsole/lastDirPath", QVariant(tabWidget.path))
self.settings.setValue("pythonConsole/lastDirPath", tabWidget.path)

def widgetMessageBar(self, iface, text, level, timed=True):
messageLevel = [QgsMessageBar.INFO, QgsMessageBar.WARNING, QgsMessageBar.CRITICAL]
Expand Down
12 changes: 6 additions & 6 deletions python/console/console_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def move_cursor_to_end(self):
def get_end_pos(self):
"""Return (line, index) position of the last character"""
line = self.sO.lines() - 1
return (line, self.sO.text(line).length())
return (line, len(self.sO.text(line)))

def flush(self):
pass
Expand Down Expand Up @@ -133,8 +133,8 @@ def __init__(self, parent=None):

def insertInitText(self):
txtInit = QCoreApplication.translate("PythonConsole",
"Python %1 on %2\n"
"## Type help(iface) for more info and list of methods.\n").arg(sys.version, socket.gethostname())
"Python {} on {}\n"
"## Type help(iface) for more info and list of methods.\n".format(sys.version, socket.gethostname()))
initText = self.setText(txtInit)

def refreshLexerProperties(self):
Expand All @@ -143,8 +143,8 @@ def refreshLexerProperties(self):
def setLexers(self):
self.lexer = QsciLexerPython()

loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace").toString()
fontSize = self.settings.value("pythonConsole/fontsize", 10).toInt()[0]
loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace")
fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int)
font = QFont(loadFont)
font.setFixedPitch(True)
font.setPointSize(fontSize)
Expand Down Expand Up @@ -252,7 +252,7 @@ def enteredSelected(self):
def keyPressEvent(self, e):
# empty text indicates possible shortcut key sequence so stay in output
txt = e.text()
if txt.length() and txt >= " ":
if len(txt) and txt >= " ":
self.shell.append(txt)
self.shell.move_cursor_to_end()
self.shell.setFocus()
Expand Down
46 changes: 23 additions & 23 deletions python/console/console_sci.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def __init__(self, parent=None):
for line in _init_commands:
self.runsource(line)

self.history = QStringList()
self.history = []
self.historyIndex = 0
# Read history command file
self.readHistoryFile()
Expand Down Expand Up @@ -114,10 +114,10 @@ def __init__(self, parent=None):
def settingsShell(self):
# Set Python lexer
self.setLexers()
threshold = self.settings.value("pythonConsole/autoCompThreshold", 2).toInt()[0]
threshold = self.settings.value("pythonConsole/autoCompThreshold", 2, type=int)
self.setAutoCompletionThreshold(threshold)
radioButtonSource = self.settings.value("pythonConsole/autoCompleteSource", 'fromAPI').toString()
autoCompEnabled = self.settings.value("pythonConsole/autoCompleteEnabled", True).toBool()
radioButtonSource = self.settings.value("pythonConsole/autoCompleteSource", 'fromAPI')
autoCompEnabled = self.settings.value("pythonConsole/autoCompleteEnabled", True)
if autoCompEnabled:
if radioButtonSource == 'fromDoc':
self.setAutoCompletionSource(self.AcsDocument)
Expand All @@ -135,8 +135,8 @@ def showHistory(self):
self.historyDlg.activateWindow()

def autoCompleteKeyBinding(self):
radioButtonSource = self.settings.value("pythonConsole/autoCompleteSource").toString()
autoCompEnabled = self.settings.value("pythonConsole/autoCompleteEnabled").toBool()
radioButtonSource = self.settings.value("pythonConsole/autoCompleteSource")
autoCompEnabled = self.settings.value("pythonConsole/autoCompleteEnabled")
if autoCompEnabled:
if radioButtonSource == 'fromDoc':
self.autoCompleteFromDocument()
Expand All @@ -149,7 +149,7 @@ def commandConsole(self, command):
if not self.is_cursor_on_last_line():
self.move_cursor_to_end()
line, pos = self.getCursorPosition()
selCmdLenght = self.text(line).length()
selCmdLenght = len(self.text(line))
self.setSelection(line, 4, line, selCmdLenght)
self.removeSelectedText()
if command == "sextante":
Expand All @@ -168,8 +168,8 @@ def commandConsole(self, command):
def setLexers(self):
self.lexer = QsciLexerPython()

loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace").toString()
fontSize = self.settings.value("pythonConsole/fontsize", 10).toInt()[0]
loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace")
fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int)

font = QFont(loadFont)
font.setFixedPitch(True)
Expand All @@ -188,13 +188,13 @@ def setLexers(self):
self.lexer.setFont(font, 4)

self.api = QsciAPIs(self.lexer)
chekBoxAPI = self.settings.value("pythonConsole/preloadAPI", True).toBool()
chekBoxAPI = self.settings.value("pythonConsole/preloadAPI", True)
if chekBoxAPI:
self.api.loadPrepared( QgsApplication.pkgDataPath() + "/python/qsci_apis/pyqgis_master.pap" )
else:
apiPath = self.settings.value("pythonConsole/userAPI").toStringList()
apiPath = self.settings.value("pythonConsole/userAPI")
for i in range(0, len(apiPath)):
self.api.load(QString(unicode(apiPath[i])))
self.api.load(unicode(apiPath[i]))
self.api.prepare()
self.lexer.setAPIs(self.api)

Expand Down Expand Up @@ -223,7 +223,7 @@ def getTextLength(self):
def get_end_pos(self):
"""Return (line, index) position of the last character"""
line = self.lines() - 1
return (line, self.text(line).length())
return (line, len(self.text(line)))

def is_cursor_at_end(self):
"""Return True if cursor is at the end of text"""
Expand Down Expand Up @@ -262,7 +262,7 @@ def displayPrompt(self, more=False):
self.move_cursor_to_end()

def updateHistory(self, command):
if isinstance(command, QStringList):
if isinstance(command, list):
for line in command:
self.history.append(line)
elif not command == "":
Expand Down Expand Up @@ -299,7 +299,7 @@ def readHistoryFile(self):

def clearHistory(self, clearSession=False):
if clearSession:
self.history = QStringList()
self.history = []
msgText = QCoreApplication.translate('PythonConsole',
'Session and file history cleared successfully.')
self.parent.callWidgetMessageBar(msgText)
Expand All @@ -320,9 +320,9 @@ def clearHistorySession(self):
self.clearHistory(True)

def showPrevious(self):
if self.historyIndex < len(self.history) and not self.history.isEmpty():
if self.historyIndex < len(self.history) and self.history:
line, pos = self.getCursorPosition()
selCmdLenght = self.text(line).length()
selCmdLenght = len(self.text(line))
self.setSelection(line, 4, line, selCmdLenght)
self.removeSelectedText()
self.historyIndex += 1
Expand All @@ -335,9 +335,9 @@ def showPrevious(self):
#self.SendScintilla(QsciScintilla.SCI_DELETEBACK)

def showNext(self):
if self.historyIndex > 0 and not self.history.isEmpty():
if self.historyIndex > 0 and self.history:
line, pos = self.getCursorPosition()
selCmdLenght = self.text(line).length()
selCmdLenght = len(self.text(line))
self.setSelection(line, 4, line, selCmdLenght)
self.removeSelectedText()
self.historyIndex -= 1
Expand Down Expand Up @@ -406,7 +406,7 @@ def keyPressEvent(self, e):
self.showNext()
## TODO: press event for auto-completion file directory
else:
if self.settings.value("pythonConsole/autoCloseBracket", True).toBool():
if self.settings.value("pythonConsole/autoCloseBracket", True):
t = unicode(e.text())
## Close bracket automatically
if t in self.opening:
Expand Down Expand Up @@ -521,9 +521,9 @@ def entered(self):

def currentCommand(self):
linenr, index = self.getCursorPosition()
txtLength = self.text(linenr).length()
txtLength = len(self.text(linenr))
string = self.text()
cmdLine = string.right(txtLength - 4)
cmdLine = string[4:]
cmd = unicode(cmdLine)
return cmd

Expand Down Expand Up @@ -578,7 +578,7 @@ def __init__(self, parent):
self.reloadHistory.clicked.connect(self._reloadHistory)

def _runHistory(self, item):
cmd = item.data(Qt.DisplayRole).toString()
cmd = item.data(Qt.DisplayRole)
self.parent.runCommand(unicode(cmd))

def _reloadHistory(self):
Expand Down
66 changes: 33 additions & 33 deletions python/console/console_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def enableDisable(self, value):

def loadAPIFile(self):
settings = QSettings()
lastDirPath = settings.value("pythonConsole/lastDirAPIPath").toString()
lastDirPath = settings.value("pythonConsole/lastDirAPIPath")
fileAPI = QFileDialog.getOpenFileName(
self, "Open API File", lastDirPath, "API file (*.api)")
if fileAPI:
Expand Down Expand Up @@ -98,73 +98,73 @@ def removeAPI(self):

def saveSettings(self):
settings = QSettings()
settings.setValue("pythonConsole/preloadAPI", QVariant(self.preloadAPI.isChecked()))
settings.setValue("pythonConsole/autoSaveScript", QVariant(self.autoSaveScript.isChecked()))
settings.setValue("pythonConsole/preloadAPI", self.preloadAPI.isChecked())
settings.setValue("pythonConsole/autoSaveScript", self.autoSaveScript.isChecked())

fontFamilyText = self.fontComboBox.currentText()
settings.setValue("pythonConsole/fontfamilytext", QVariant(fontFamilyText))
settings.setValue("pythonConsole/fontfamilytext", fontFamilyText)
fontFamilyTextEditor = self.fontComboBoxEditor.currentText()
settings.setValue("pythonConsole/fontfamilytextEditor", QVariant(fontFamilyTextEditor))
settings.setValue("pythonConsole/fontfamilytextEditor", fontFamilyTextEditor)

fontSize = self.spinBox.value()
fontSizeEditor = self.spinBoxEditor.value()

for i in range(0, self.tableWidget.rowCount()):
text = self.tableWidget.item(i, 1).text()
self.listPath.append(text)
settings.setValue("pythonConsole/fontsize", QVariant(fontSize))
settings.setValue("pythonConsole/fontsizeEditor", QVariant(fontSizeEditor))
settings.setValue("pythonConsole/userAPI", QVariant(self.listPath))
settings.setValue("pythonConsole/fontsize", fontSize)
settings.setValue("pythonConsole/fontsizeEditor", fontSizeEditor)
settings.setValue("pythonConsole/userAPI", self.listPath)

settings.setValue("pythonConsole/autoCompThreshold", QVariant(self.autoCompThreshold.value()))
settings.setValue("pythonConsole/autoCompThresholdEditor", QVariant(self.autoCompThresholdEditor.value()))
settings.setValue("pythonConsole/autoCompThreshold", self.autoCompThreshold.value())
settings.setValue("pythonConsole/autoCompThresholdEditor", self.autoCompThresholdEditor.value())

settings.setValue("pythonConsole/autoCompleteEnabledEditor", QVariant(self.groupBoxAutoCompletionEditor.isChecked()))
settings.setValue("pythonConsole/autoCompleteEnabled", QVariant(self.groupBoxAutoCompletion.isChecked()))
settings.setValue("pythonConsole/autoCompleteEnabledEditor", self.groupBoxAutoCompletionEditor.isChecked())
settings.setValue("pythonConsole/autoCompleteEnabled", self.groupBoxAutoCompletion.isChecked())

if self.autoCompFromAPIEditor.isChecked():
settings.setValue("pythonConsole/autoCompleteSourceEditor", QVariant('fromAPI'))
settings.setValue("pythonConsole/autoCompleteSourceEditor", 'fromAPI')
elif self.autoCompFromDocEditor.isChecked():
settings.setValue("pythonConsole/autoCompleteSourceEditor", QVariant('fromDoc'))
settings.setValue("pythonConsole/autoCompleteSourceEditor", 'fromDoc')
elif self.autoCompFromDocAPIEditor.isChecked():
settings.setValue("pythonConsole/autoCompleteSourceEditor", QVariant('fromDocAPI'))
settings.setValue("pythonConsole/autoCompleteSourceEditor", 'fromDocAPI')

if self.autoCompFromAPI.isChecked():
settings.setValue("pythonConsole/autoCompleteSource", QVariant('fromAPI'))
settings.setValue("pythonConsole/autoCompleteSource", 'fromAPI')
elif self.autoCompFromDoc.isChecked():
settings.setValue("pythonConsole/autoCompleteSource", QVariant('fromDoc'))
settings.setValue("pythonConsole/autoCompleteSource", 'fromDoc')
elif self.autoCompFromDocAPI.isChecked():
settings.setValue("pythonConsole/autoCompleteSource", QVariant('fromDocAPI'))
settings.setValue("pythonConsole/autoCompleteSource", 'fromDocAPI')

settings.setValue("pythonConsole/enableObjectInsp", QVariant(self.enableObjectInspector.isChecked()))
settings.setValue("pythonConsole/autoCloseBracket", QVariant(self.autoCloseBracket.isChecked()))
settings.setValue("pythonConsole/autoCloseBracketEditor", QVariant(self.autoCloseBracketEditor.isChecked()))
settings.setValue("pythonConsole/enableObjectInsp", self.enableObjectInspector.isChecked())
settings.setValue("pythonConsole/autoCloseBracket", self.autoCloseBracket.isChecked())
settings.setValue("pythonConsole/autoCloseBracketEditor", self.autoCloseBracketEditor.isChecked())

def restoreSettings(self):
settings = QSettings()
self.spinBox.setValue(settings.value("pythonConsole/fontsize", 10).toInt()[0])
self.spinBoxEditor.setValue(settings.value("pythonConsole/fontsizeEditor", 10).toInt()[0])
self.spinBox.setValue(settings.value("pythonConsole/fontsize", 10, type=int))
self.spinBoxEditor.setValue(settings.value("pythonConsole/fontsizeEditor", 10, type=int))
self.fontComboBox.setCurrentFont(QFont(settings.value("pythonConsole/fontfamilytext",
"Monospace").toString()))
"Monospace")))
self.fontComboBoxEditor.setCurrentFont(QFont(settings.value("pythonConsole/fontfamilytextEditor",
"Monospace").toString()))
self.preloadAPI.setChecked(settings.value("pythonConsole/preloadAPI", True).toBool())
itemTable = settings.value("pythonConsole/userAPI").toStringList()
"Monospace")))
self.preloadAPI.setChecked(settings.value("pythonConsole/preloadAPI", True, type=bool))
itemTable = settings.value("pythonConsole/userAPI", [])
for i in range(len(itemTable)):
self.tableWidget.insertRow(i)
self.tableWidget.setColumnCount(2)
pathSplit = itemTable[i].split("/")
apiName = pathSplit[-1][0:-4]
self.tableWidget.setItem(i, 0, QTableWidgetItem(apiName))
self.tableWidget.setItem(i, 1, QTableWidgetItem(itemTable[i]))
self.autoSaveScript.setChecked(settings.value("pythonConsole/autoSaveScript", False).toBool())
self.autoSaveScript.setChecked(settings.value("pythonConsole/autoSaveScript", False, type=bool))

self.autoCompThreshold.setValue(settings.value("pythonConsole/autoCompThreshold", 2).toInt()[0])
self.autoCompThresholdEditor.setValue(settings.value("pythonConsole/autoCompThresholdEditor", 2).toInt()[0])
self.autoCompThreshold.setValue(settings.value("pythonConsole/autoCompThreshold", 2, type=int))
self.autoCompThresholdEditor.setValue(settings.value("pythonConsole/autoCompThresholdEditor", 2, type=int))

self.enableObjectInspector.setChecked(settings.value("pythonConsole/enableObjectInsp", False).toBool())
self.autoCloseBracketEditor.setChecked(settings.value("pythonConsole/autoCloseBracketEditor", True).toBool())
self.autoCloseBracket.setChecked(settings.value("pythonConsole/autoCloseBracket", True).toBool())
self.enableObjectInspector.setChecked(settings.value("pythonConsole/enableObjectInsp", False, type=bool))
self.autoCloseBracketEditor.setChecked(settings.value("pythonConsole/autoCloseBracketEditor", True, type=bool))
self.autoCloseBracket.setChecked(settings.value("pythonConsole/autoCloseBracket", True, type=bool))

if settings.value("pythonConsole/autoCompleteSource") == 'fromDoc':
self.autoCompFromDoc.setChecked(True)
Expand Down
6 changes: 3 additions & 3 deletions python/console/console_settings.ui
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@
<rect>
<x>0</x>
<y>0</y>
<width>554</width>
<height>642</height>
<width>546</width>
<height>687</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_2">
Expand Down Expand Up @@ -352,7 +352,7 @@
<string>from APIs files</string>
</property>
<property name="checked">
<bool>false</bool>
<bool>true</bool>
</property>
</widget>
</item>
Expand Down
10 changes: 5 additions & 5 deletions python/core/conversions.sip
Original file line number Diff line number Diff line change
Expand Up @@ -1014,7 +1014,7 @@ template<TYPE1, TYPE2>
TYPE1 *t1 = new TYPE1(i.key());
TYPE2 *t2 = i.value();

PyObject *t1obj = sipConvertFromNewInstance(t1, sipClass_TYPE1, sipTransferObj);
PyObject *t1obj = sipConvertFromNewType(t1, sipType_TYPE1, sipTransferObj);
PyObject *t2obj = sipConvertFromInstance(t2, sipClass_TYPE2, sipTransferObj);

if (t1obj == NULL || t2obj == NULL || PyDict_SetItem(d, t1obj, t2obj) < 0)
Expand Down Expand Up @@ -1059,7 +1059,7 @@ template<TYPE1, TYPE2>

while (PyDict_Next(sipPy, &i, &t1obj, &t2obj))
{
if (!sipCanConvertToInstance(t1obj, sipClass_TYPE1, SIP_NOT_NONE))
if (!sipCanConvertToType(t1obj, sipType_TYPE1, SIP_NOT_NONE))
return 0;

if (!sipCanConvertToInstance(t2obj, sipClass_TYPE2, SIP_NOT_NONE))
Expand All @@ -1075,12 +1075,12 @@ template<TYPE1, TYPE2>
{
int state1, state2;

TYPE1 *t1 = reinterpret_cast<TYPE1 *>(sipConvertToInstance(t1obj, sipClass_TYPE1, sipTransferObj, SIP_NOT_NONE, &state1, sipIsErr));
TYPE1 *t1 = reinterpret_cast<TYPE1 *>(sipConvertToType(t1obj, sipType_TYPE1, sipTransferObj, SIP_NOT_NONE, &state1, sipIsErr));
TYPE2 *t2 = reinterpret_cast<TYPE2 *>(sipConvertToInstance(t2obj, sipClass_TYPE2, sipTransferObj, SIP_NOT_NONE, &state2, sipIsErr));

if (*sipIsErr)
{
sipReleaseInstance(t1, sipClass_TYPE1, state1);
sipReleaseType(t1, sipType_TYPE1, state1);
sipReleaseInstance(t2, sipClass_TYPE2, state2);

delete qm;
Expand All @@ -1089,7 +1089,7 @@ template<TYPE1, TYPE2>

qm->insert(*t1, t2);

sipReleaseInstance(t1, sipClass_TYPE1, state1);
sipReleaseType(t1, sipType_TYPE1, state1);
sipReleaseInstance(t2, sipClass_TYPE2, state2);
}

Expand Down
1 change: 1 addition & 0 deletions python/core/raster/qgsrasterlayer.sip
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ class QgsRasterLayer : QgsMapLayer
// Static methods:
//
static void buildSupportedRasterFileFilter( QString & fileFilters );
static QString buildSupportedRasterFileFilter2(); /* for sip api v2 */

/** This helper checks to see whether the file name appears to be a valid
* raster file name. If the file name looks like it could be valid,
Expand Down
4 changes: 2 additions & 2 deletions python/plugins/GdalTools/GdalTools.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,11 @@ def __init__( self, iface ):
userPluginPath = QFileInfo( QgsApplication.qgisUserDbFilePath() ).path() + "/python/plugins/GdalTools"
systemPluginPath = QgsApplication.prefixPath() + "/python/plugins/GdalTools"

overrideLocale = QSettings().value( "locale/overrideFlag", QVariant( False ) ).toBool()
overrideLocale = QSettings().value( "locale/overrideFlag", False, type=bool )
if not overrideLocale:
localeFullName = QLocale.system().name()
else:
localeFullName = QSettings().value( "locale/userLocale", QVariant( "" ) ).toString()
localeFullName = QSettings().value( "locale/userLocale", "" )

if QFileInfo( userPluginPath ).exists():
translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm"
Expand Down
361 changes: 181 additions & 180 deletions python/plugins/GdalTools/tools/GdalTools_utils.py

Large diffs are not rendered by default.

36 changes: 19 additions & 17 deletions python/plugins/GdalTools/tools/dialogBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
import GdalTools_utils as Utils
from .. import resources_rc

import os, platform
import os, platform, string

class GdalToolsBaseDialog(QDialog, Ui_Dialog):

Expand All @@ -51,7 +51,7 @@ def __init__(self, parent, iface, pluginBase, pluginName, pluginCommand):
self.connect(self.process, SIGNAL("finished(int, QProcess::ExitStatus)"), self.processFinished)

self.setupUi(self)
self.arguments = QStringList()
self.arguments = []

self.editCmdBtn.setIcon( QIcon(":/icons/edit.png") )
self.connect(self.editCmdBtn, SIGNAL("toggled(bool)"), self.editCommand)
Expand All @@ -66,7 +66,7 @@ def __init__(self, parent, iface, pluginBase, pluginName, pluginCommand):
self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True)

self.plugin = pluginBase
self.connect(self.plugin, SIGNAL("valuesChanged(const QStringList &)"), self.refreshArgs)
self.connect(self.plugin, SIGNAL("valuesChanged(PyQt_PyObject)"), self.refreshArgs)

self.pluginLayout.addWidget(self.plugin)
self.plugin.setFocus()
Expand Down Expand Up @@ -138,7 +138,7 @@ def processFinished(self, exitCode, status):
# show the online tool documentation in the default browser
def onHelp(self):
helpPath = Utils.getHelpPath()
if helpPath.isEmpty():
if helpPath == '':
url = QUrl("http://www.gdal.org/" + self.helpFileName)
else:
url = QUrl.fromLocalFile(helpPath + '/' + self.helpFileName)
Expand All @@ -162,6 +162,7 @@ def onRun(self):
self.enableRun(False)
self.setCursor(Qt.WaitCursor)
if not self.commandIsEditable():
#print(self.command+' '+str(self.arguments))
self.process.start(self.command, self.arguments, QIODevice.ReadOnly)
else:
self.process.start(self.textEditCommand.toPlainText(), QIODevice.ReadOnly)
Expand Down Expand Up @@ -204,23 +205,24 @@ def onFinished(self, exitCode, status):
return

# show the error message if there's one, otherwise show the process output message
msg = QString.fromLocal8Bit(self.process.readAllStandardError())
if msg.isEmpty():
outMessages = QString.fromLocal8Bit(self.process.readAllStandardOutput()).split( "\n" )
msg = str(self.process.readAllStandardError())
if msg == '':
outMessages = string.split( str(self.process.readAllStandardOutput()), sep="\n" )

# make sure to not show the help
for m in outMessages:
m = m.trimmed()
if m.isEmpty():
m = string.strip(m)
if m == '':
continue
if m.contains( QRegExp( "^(?:[Uu]sage:\\s)?" + QRegExp.escape(self.command) + "\\s" ) ):
if msg.isEmpty():
msg = self.tr ( "Invalid parameters." )
break
if m.contains( QRegExp( "0(?:\\.+[1-9]0{1,2})+" ) ):
continue

if not msg.isEmpty():
# TODO fix this
#if m.contains( QRegExp( "^(?:[Uu]sage:\\s)?" + QRegExp.escape(self.command) + "\\s" ) ):
# if msg.isEmpty():
# msg = self.tr ( "Invalid parameters." )
# break
#if m.contains( QRegExp( "0(?:\\.+[1-9]0{1,2})+" ) ):
# continue

if not msg == '':
msg += "\n"
msg += m

Expand Down
2 changes: 1 addition & 1 deletion python/plugins/GdalTools/tools/dialogSRS.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,4 @@ def getProjection(self):
if not self.selector.selectedProj4String().isEmpty():
return self.proj4string()

return QString()
return ''
36 changes: 18 additions & 18 deletions python/plugins/GdalTools/tools/doBuildVRT.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def __init__(self, iface):
self.inSelector.setType( self.inSelector.FILE )
self.outSelector.setType( self.outSelector.FILE )
self.recurseCheck.hide()
self.visibleRasterLayers = QStringList()
self.visibleRasterLayers = []

self.setParamsStatus(
[
Expand Down Expand Up @@ -82,10 +82,10 @@ def onClosing(self):

def onVisibleLayersChanged(self):
# refresh list of visible raster layers
self.visibleRasterLayers = QStringList()
self.visibleRasterLayers = []
for layer in self.iface.mapCanvas().layers():
if Utils.LayerRegistry.isRaster( layer ):
self.visibleRasterLayers << layer.source()
self.visibleRasterLayers.append( layer.source() )

# refresh the text in the command viewer
self.someValueChanged()
Expand Down Expand Up @@ -115,42 +115,42 @@ def switchLayerMode(self):
def fillInputFilesEdit(self):
lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter()
files = Utils.FileDialog.getOpenFileNames(self, self.tr( "Select the files for VRT" ), Utils.FileFilter.allRastersFilter(), lastUsedFilter)
if files.isEmpty():
if files == '':
return
Utils.FileFilter.setLastUsedRasterFilter(lastUsedFilter)
self.inSelector.setFilename(files.join(","))
self.inSelector.setFilename(",".join(files))

def fillOutputFileEdit(self):
outputFile = Utils.FileDialog.getSaveFileName(self, self.tr( "Select where to save the VRT" ), self.tr( "VRT (*.vrt)" ))
if outputFile.isEmpty():
if outputFile == '':
return
self.outSelector.setFilename(outputFile)

def fillInputDir( self ):
inputDir = Utils.FileDialog.getExistingDirectory( self, self.tr( "Select the input directory with files for VRT" ))
if inputDir.isEmpty():
if inputDir == '':
return
self.inSelector.setFilename( inputDir )

def getArguments(self):
arguments = QStringList()
arguments = []
if self.resolutionCheck.isChecked() and self.resolutionComboBox.currentIndex() >= 0:
arguments << "-resolution"
arguments << self.resolutions[self.resolutionComboBox.currentIndex()]
arguments.append("-resolution")
arguments.append(self.resolutions[self.resolutionComboBox.currentIndex()])
if self.separateCheck.isChecked():
arguments << "-separate"
arguments.append("-separate")
if self.srcNoDataCheck.isChecked():
arguments << "-srcnodata"
arguments << str(self.srcNoDataSpin.value())
arguments.append("-srcnodata")
arguments.append(str(self.srcNoDataSpin.value()))
if self.allowProjDiffCheck.isChecked():
arguments << "-allow_projection_difference"
arguments << self.getOutputFileName()
arguments.append("-allow_projection_difference")
arguments.append(self.getOutputFileName())
if self.inputSelLayersCheck.isChecked():
arguments << self.visibleRasterLayers
arguments.extend(self.visibleRasterLayers)
elif self.inputDirCheck.isChecked():
arguments << Utils.getRasterFiles( self.getInputFileName(), self.recurseCheck.isChecked() )
arguments.extend(Utils.getRasterFiles( self.getInputFileName(), self.recurseCheck.isChecked() ))
else:
arguments << self.getInputFileName()
arguments.extend(self.getInputFileName())
return arguments

def getOutputFileName(self):
Expand Down
60 changes: 30 additions & 30 deletions python/plugins/GdalTools/tools/doClipper.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def checkRun(self):
if self.extentModeRadio.isChecked():
enabler = self.extentSelector.isCoordsValid()
else:
enabler = not self.maskSelector.filename().isEmpty()
enabler = not self.maskSelector.filename() == ''
self.base.enableRun( enabler )

def extentChanged(self):
Expand All @@ -104,7 +104,7 @@ def onLayersChanged(self):
def fillInputFileEdit(self):
lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter()
inputFile = Utils.FileDialog.getOpenFileName(self, self.tr( "Select the input file for Polygonize" ), Utils.FileFilter.allRastersFilter(), lastUsedFilter )
if inputFile.isEmpty():
if inputFile == '':
return
Utils.FileFilter.setLastUsedRasterFilter(lastUsedFilter)

Expand All @@ -113,7 +113,7 @@ def fillInputFileEdit(self):
def fillOutputFileEdit(self):
lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter()
outputFile = Utils.FileDialog.getSaveFileName(self, self.tr( "Select the raster file to save the results to" ), Utils.FileFilter.allRastersFilter(), lastUsedFilter)
if outputFile.isEmpty():
if outputFile == '':
return
Utils.FileFilter.setLastUsedRasterFilter(lastUsedFilter)

Expand All @@ -123,7 +123,7 @@ def fillOutputFileEdit(self):
def fillMaskFileEdit(self):
lastUsedFilter = Utils.FileFilter.lastUsedVectorFilter()
maskFile = Utils.FileDialog.getOpenFileName(self, self.tr( "Select the mask file" ), Utils.FileFilter.allVectorsFilter(), lastUsedFilter )
if maskFile.isEmpty():
if maskFile == '':
return
Utils.FileFilter.setLastUsedVectorFilter(lastUsedFilter)

Expand All @@ -137,48 +137,48 @@ def getArguments(self):

def getArgsModeExtent(self):
self.base.setPluginCommand( "gdal_translate" )
arguments = QStringList()
arguments = []
if self.noDataCheck.isChecked():
arguments << "-a_nodata"
arguments.append("-a_nodata")
arguments << str(self.noDataSpin.value())
if self.extentModeRadio.isChecked() and self.extentSelector.isCoordsValid():
rect = self.extentSelector.getExtent()
if rect != None:
arguments << "-projwin"
arguments << str(rect.xMinimum())
arguments << str(rect.yMaximum())
arguments << str(rect.xMaximum())
arguments << str(rect.yMinimum())
if not self.getOutputFileName().isEmpty():
arguments << "-of"
arguments << self.outputFormat
arguments << self.getInputFileName()
arguments << self.getOutputFileName()
arguments.append("-projwin")
arguments.append(str(rect.xMinimum()))
arguments.append(str(rect.yMaximum()))
arguments.append(str(rect.xMaximum()))
arguments.append(str(rect.yMinimum()))
if not self.getOutputFileName() == '':
arguments.append("-of")
arguments.append(self.outputFormat)
arguments.append(self.getInputFileName())
arguments.append(self.getOutputFileName())
return arguments

def getArgsModeMask(self):
self.base.setPluginCommand( "gdalwarp" )
arguments = QStringList()
arguments = []
if self.noDataCheck.isChecked():
arguments << "-dstnodata"
arguments << str(self.noDataSpin.value())
arguments.append("-dstnodata")
arguments.append(str(self.noDataSpin.value()))
if self.maskModeRadio.isChecked():
mask = self.maskSelector.filename()
if not mask.isEmpty():
arguments << "-q"
arguments << "-cutline"
arguments << mask
if not mask == '':
arguments.append("-q")
arguments.append("-cutline")
arguments.append(mask)
if Utils.GdalConfig.version() >= "1.8.0":
arguments << "-crop_to_cutline"
arguments.append("-crop_to_cutline")
if self.alphaBandCheck.isChecked():
arguments << "-dstalpha"
arguments.append("-dstalpha")

outputFn = self.getOutputFileName()
if not outputFn.isEmpty():
arguments << "-of"
arguments << self.outputFormat
arguments << self.getInputFileName()
arguments << outputFn
if not outputFn == '':
arguments.append("-of")
arguments.append(self.outputFormat)
arguments.append(self.getInputFileName())
arguments.append(outputFn)
return arguments

def getOutputFileName(self):
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/GdalTools/tools/doContour.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def getArguments(self):
arguments << self.attributeEdit.text()
if True: # XXX in this moment the -i argument is not optional
arguments << "-i"
arguments << QString(str(self.intervalDSpinBox.value()))
arguments << unicode(self.intervalDSpinBox.value())
arguments << self.getInputFileName()
arguments << self.outSelector.filename()
return arguments
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/GdalTools/tools/doGrid.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ def algorithmArguments(self, index):
arguments.append("nodata=" + str(self.datametricsNoDataSpin.value()))
return arguments.join(":")

def loadFields(self, vectorFile = QString()):
def loadFields(self, vectorFile = ''):
self.zfieldCombo.clear()

if vectorFile.isEmpty():
Expand Down
24 changes: 13 additions & 11 deletions python/plugins/GdalTools/tools/doInfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import GdalTools_utils as Utils

import platform
import string

class GdalToolsDialog( QWidget, Ui_Widget, BasePluginWidget ):

Expand Down Expand Up @@ -66,7 +67,7 @@ def __init__( self, iface ):


def doCopyLine( self ):
output = QString()
output = ''
items = self.rasterInfoList.selectedItems()
for r in items:
output.append( r.text() + "\n" )
Expand All @@ -75,7 +76,7 @@ def doCopyLine( self ):
clipboard.setText( output )

def doCopyAll( self ):
output = QString()
output = ''
for r in range( self.rasterInfoList.count() ):
output.append( self.rasterInfoList.item( r ).text() + "\n" )
if not output.isEmpty():
Expand All @@ -84,7 +85,7 @@ def doCopyAll( self ):

def keyPressEvent( self, e ):
if ( e.modifiers() == Qt.ControlModifier or e.modifiers() == Qt.MetaModifier ) and e.key() == Qt.Key_C:
items = QString()
items = ''
for r in range( self.rasterInfoList.count() ):
items.append( self.rasterInfoList.item( r ).text() + "\n" )
if not items.isEmpty():
Expand All @@ -98,12 +99,13 @@ def onLayersChanged(self):

def finished( self ):
self.rasterInfoList.clear()
arr = QByteArray()
arr = self.base.process.readAllStandardOutput()
arr = str(self.base.process.readAllStandardOutput()).strip()
if platform.system() == "Windows":
info = QString.fromLocal8Bit( arr ).trimmed().split( "\r\n" )
#info = QString.fromLocal8Bit( arr ).trimmed().split( "\r\n" )
# TODO test
info = string.split(arr, sep="\r\n" )
else:
info = QString( arr ).trimmed().split( "\n" )
info = string.split(arr, sep="\n" )
self.rasterInfoList.addItems( info )

def fillInputFileEdit( self ):
Expand All @@ -116,12 +118,12 @@ def fillInputFileEdit( self ):
self.inSelector.setFilename( inputFile )

def getArguments( self ):
arguments = QStringList()
arguments = []
if self.suppressGCPCheck.isChecked():
arguments << "-nogcp"
arguments.append("-nogcp")
if self.suppressMDCheck.isChecked():
arguments << "-nomd"
arguments << self.getInputFileName()
arguments.append("-nomd")
arguments.append(self.getInputFileName())
return arguments

# def getOutputFileName( self ):
Expand Down
64 changes: 34 additions & 30 deletions python/plugins/GdalTools/tools/doOverview.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ def __init__( self, iface ):

# set the default QSpinBoxes and QProgressBar value
self.progressBar.setValue(0)
self.jpegQualitySpin.setValue(80)

self.progressBar.hide()
# we don't need load to canvas functionality
Expand All @@ -55,13 +54,6 @@ def __init__( self, iface ):
self.setParamsStatus(
[
( self.inSelector, SIGNAL("filenameChanged()")),
( self.algorithmCombo, SIGNAL( "currentIndexChanged( int )" ), self.algorithmCheck ),
( self.levelsEdit, SIGNAL( "textChanged( const QString & )" ) ),
( self.roModeCheck, SIGNAL( "stateChanged( int )" ), None, 1600 ),
( self.rrdCheck, SIGNAL( "stateChanged(int)" ) ),
( self.jpegQualitySpin, SIGNAL( "valueChanged (int)" ) ),
( self.jpegQualityContainer, None, self.tiffjpegCheck),
( self.jpegQualityContainer, None, None, 1700),
( self.cleanCheck, SIGNAL( "stateChanged(int)" ), None, 1700 ),
( self.mPyramidOptionsWidget, SIGNAL( "overviewListChanged()" )),
( self.mPyramidOptionsWidget, SIGNAL( "someValueChanged()" ))
Expand All @@ -73,6 +65,11 @@ def __init__( self, iface ):

self.init = False #workaround bug that pyramid options widgets are not initialized at first

# make sure we get a command line when dialog appears
def show_(self):
BaseBatchWidget.show_(self)
self.someValueChanged()

# switch to batch or normal mode
def switchToolMode( self ):
self.setCommandViewerEnabled( not self.batchCheck.isChecked() )
Expand All @@ -98,7 +95,7 @@ def onLayersChanged(self):
def fillInputFile( self ):
lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter()
inputFile = Utils.FileDialog.getOpenFileName( self, self.tr( "Select the input file" ), Utils.FileFilter.allRastersFilter(), lastUsedFilter )
if inputFile.isEmpty():
if inputFile == '':
return
Utils.FileFilter.setLastUsedRasterFilter( lastUsedFilter )

Expand All @@ -108,39 +105,45 @@ def fillInputFile( self ):

def fillInputDir( self ):
inputDir = Utils.FileDialog.getExistingDirectory( self, self.tr( "Select the input directory with files" ))
if inputDir.isEmpty():
if inputDir == '':
return

self.inSelector.setFilename( inputDir )

def getArguments( self ):
arguments = QStringList()
arguments = []

arguments << "-r"
arguments << self.mPyramidOptionsWidget.resamplingMethod();
arguments.append("-r")
arguments.append(self.mPyramidOptionsWidget.resamplingMethod())

format = self.mPyramidOptionsWidget.pyramidsFormat()
if format == QgsRasterDataProvider.PyramidsGTiff:
arguments << "-ro"
elif format == QgsRasterDataProvider.PyramidsErdas:
arguments << "--config" << "USE_RRD" << "YES"
if format == QgsRaster.PyramidsGTiff:
arguments.append("-ro")
elif format == QgsRaster.PyramidsErdas:
arguments.append("--config")
arguments.append("USE_RRD")
arguments.append("YES")

for option in self.mPyramidOptionsWidget.configOptions():
(k,v) = option.split("=")
arguments << "--config" << str(k) << str(v)
arguments.append("--config")
arguments.append(str(k))
arguments.append(str(v))

if self.cleanCheck.isChecked():
arguments << "-clean"
arguments.append("-clean")

# TODO fix batch enabled, argument order is wrong, levels not at end
if self.isBatchEnabled():
return arguments

arguments << self.getInputFileName()
arguments.append(self.getInputFileName())

if len(self.mPyramidOptionsWidget.overviewList()) == 0:
arguments << "[levels]"
for level in self.mPyramidOptionsWidget.overviewList():
arguments << str(level)
arguments.append(self.tr("[select levels]"))
else:
for level in self.mPyramidOptionsWidget.overviewList():
arguments.append(str(level))

# set creation options filename/layer for validation
if self.init:
Expand All @@ -166,11 +169,12 @@ def addLayerIntoCanvas(self, fileInfo):

def getBatchArguments(self, inFile, outFile = None):
arguments = self.getArguments()
arguments << inFile
if not self.levelsEdit.text().isEmpty():
arguments << self.levelsEdit.text().split( " " )
arguments.append(inFile)
if len(self.mPyramidOptionsWidget.overviewList()) == 0:
arguments.extend(["2", "4", "8", "16", "32"])
else:
arguments << "2" << "4" << "8" << "16" << "32"
for level in self.mPyramidOptionsWidget.overviewList():
arguments.append(str(level))
return arguments

def isBatchEnabled(self):
Expand All @@ -182,8 +186,8 @@ def onFinished(self, exitCode, status):
BasePluginWidget.onFinished(self, exitCode, status)
return

msg = QString.fromLocal8Bit( self.base.process.readAllStandardError() )
if not msg.isEmpty():
msg = str( self.base.process.readAllStandardError() )
if msg != '':
self.errors.append( ">> " + self.inFiles[self.batchIndex] + "<br>" + msg.replace( "\n", "<br>" ) )

self.base.process.close()
Expand Down
4 changes: 2 additions & 2 deletions python/plugins/GdalTools/tools/doProjection.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def getArguments( self ):

inputFn = self.getInputFileName()
arguments << inputFn
self.tempFile = QString( inputFn )
self.tempFile = inputFn
self.needOverwrite = False
if not self.tempFile.isEmpty():
if self.tempFile.toLower().contains( QRegExp( "\.tif{1,2}" ) ):
Expand Down Expand Up @@ -157,7 +157,7 @@ def getOutputFileName( self ):

def getBatchOutputFileName(self, fn):
# get GeoTiff
fn = QString( fn ).replace( QRegExp( "\.[a-zA-Z]{2,4}$" ), ".tif" )
fn = re.sub( r'\.[a-zA-Z]{2,4}$', r'.tif', fn )
return BaseBatchWidget.getBatchOutputFileName( self, fn )

def addLayerIntoCanvas(self, fileInfo):
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/GdalTools/tools/doTranslate.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def fillInputDir( self ):
workDir.setNameFilters( filter )

# search for a valid SRS, then use it as default target SRS
srs = QString()
srs = ''
for fname in workDir.entryList():
fl = inputDir + "/" + fname
srs = Utils.getRasterSRS( self, fl )
Expand Down
35 changes: 18 additions & 17 deletions python/plugins/GdalTools/tools/inOutSelector.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,14 @@ def __init__(self, parent = None, type=None):
self.connect(self.combo, SIGNAL("currentIndexChanged(int)"), self.indexChanged)

def clear(self):
self.filenames = QStringList()
self.filenames = []
self.fileEdit.clear()
self.clearComboState()
self.combo.clear()

def textChanged(self):
if self.getType() & self.MULTIFILE:
self.filenames = QStringList() << self.fileEdit.text().split(",")
self.filenames = self.fileEdit.text().split(",")
if self.getType() & self.LAYER:
index = self.combo.currentIndex()
if index >= 0:
Expand Down Expand Up @@ -132,20 +132,21 @@ def setFilename(self, fn=None):
if isinstance(fn, QgsMapLayer):
fn = fn.source()

elif isinstance(fn, str) or isinstance(fn, unicode) or isinstance(fn, QString):
fn = QString( fn )
elif isinstance(fn, str) or isinstance(fn, unicode):
fn = unicode( fn )

elif hasattr(fn, '__iter__') or isinstance(fn, QStringList):
if len( fn ) > 0:
fn = QStringList() << fn
if self.getType() & self.MULTIFILE:
self.filenames = fn
fn = fn.join( "," )
else:
fn = QString()
#TODO fix and test
#elif hasattr(fn, '__iter__') or isinstance(fn, QStringList):
# if len( fn ) > 0:
# fn = QStringList() << fn
# if self.getType() & self.MULTIFILE:
# self.filenames = fn
# fn = fn.join( "," )
# else:
# fn = ''

else:
fn = QString()
fn = ''

if not (self.getType() & self.LAYER):
self.fileEdit.setText( fn )
Expand Down Expand Up @@ -215,7 +216,7 @@ def clearComboState(self):
def saveComboState(self):
index = self.combo.currentIndex()
text = self.combo.currentText()
layerID = self.combo.itemData(index).toString() if index >= 0 else ""
layerID = self.combo.itemData(index) if index >= 0 else ""
self.prevState = ( index, text, layerID )

def restoreComboState(self):
Expand All @@ -224,7 +225,7 @@ def restoreComboState(self):
index, text, layerID = self.prevState

if index < 0:
if text.isEmpty() and self.combo.count() > 0:
if text == '' and self.combo.count() > 0:
index = 0

elif self.combo.findData( layerID ) < 0:
Expand All @@ -241,7 +242,7 @@ def restoreComboState(self):

def layer(self):
if self.getType() != self.FILE and self.combo.currentIndex() >= 0:
layerID = self.combo.itemData(self.combo.currentIndex()).toString()
layerID = self.combo.itemData(self.combo.currentIndex())
return QgsMapLayerRegistry.instance().mapLayer( layerID )
return None

Expand All @@ -259,5 +260,5 @@ def filename(self):
if layer != None:
return layer.source()

return QString()
return ''

28 changes: 14 additions & 14 deletions python/plugins/GdalTools/tools/widgetBatchBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ def __init__(self, iface, commandName):
BasePluginWidget.__init__(self, iface, commandName)

def getBatchArguments(self, inFile, outFile = None):
arguments = QStringList()
arguments << self.getArguments()
arguments << inFile
arguments = []
arguments.extend( self.getArguments() )
arguments.append( inFile )
if outFile != None:
arguments << outFile
arguments.append(outFile)
return arguments

def isBatchEnabled(self):
Expand All @@ -62,9 +62,9 @@ def getBatchOutputFileName(self, fn):

# if overwrites existent files
if outDir == None or outDir == inDir:
return QString( fn ).append( ".tmp" )
return fn + ".tmp"

return QString( fn ).mid( len(inDir) ).prepend( outDir )
return outDir + fn[len(inDir):]

def onRun( self ):
if not self.isBatchEnabled():
Expand All @@ -85,7 +85,7 @@ def batchRun(self):
for f in self.inFiles:
self.outFiles.append( self.getBatchOutputFileName( f ) )

self.errors = QStringList()
self.errors = []
self.batchIndex = 0
self.batchTotal = len( self.inFiles )
self.setProgressRange( self.batchTotal )
Expand All @@ -112,8 +112,8 @@ def onFinished(self, exitCode, status):
BasePluginWidget.onFinished(self, exitCode, status)
return

msg = QString.fromLocal8Bit( self.base.process.readAllStandardError() )
if not msg.isEmpty():
msg = bytes.decode( bytes( self.base.process.readAllStandardError() ) )
if msg != '':
self.errors.append( ">> " + self.inFiles[self.batchIndex] + "<br>" + msg.replace( "\n", "<br>" ) )

self.base.process.close()
Expand All @@ -133,8 +133,8 @@ def onFinished(self, exitCode, status):
def batchFinished( self ):
self.base.stop()

if not self.errors.isEmpty():
msg = QString( "Processing of the following files ended with error: <br><br>" ).append( self.errors.join( "<br><br>" ) )
if len(self.errors) > 0:
msg = u"Processing of the following files ended with error: <br><br>" + "<br><br>".join( self.errors )
QErrorMessage( self ).showMessage( msg )

inDir = self.getInputFileName()
Expand All @@ -146,17 +146,17 @@ def batchFinished( self ):
canvas = self.iface.mapCanvas()
previousRenderFlag = canvas.renderFlag()
canvas.setRenderFlag( False )
notCreatedList = QStringList()
notCreatedList = []
for item in self.outFiles:
fileInfo = QFileInfo( item )
if fileInfo.exists():
if self.base.loadCheckBox.isChecked():
self.addLayerIntoCanvas( fileInfo )
else:
notCreatedList << item
notCreatedList.append( item )
canvas.setRenderFlag( previousRenderFlag )

if notCreatedList.isEmpty():
if len( notCreatedList ) == 0:
QMessageBox.information( self, self.tr( "Finished" ), self.tr( "Operation completed." ) )
else:
QMessageBox.warning( self, self.tr( "Warning" ), self.tr( "The following files were not created: \n%1" ).arg( notCreatedList.join( ", " ) ) )
Expand Down
185 changes: 9 additions & 176 deletions python/plugins/GdalTools/tools/widgetOverview.ui
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QCheckBox" name="batchCheck">
<property name="enabled">
<bool>true</bool>
</property>
<property name="text">
<string>Batch mode (for processing whole directory)</string>
</property>
Expand Down Expand Up @@ -55,183 +58,13 @@
</widget>
</item>
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
<widget class="QgsRasterPyramidsOptionsWidget" name="mPyramidOptionsWidget" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<widget class="QWidget" name="tab">
<attribute name="title">
<string>old</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_2">
<item row="2" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Levels (space delimited)</string>
</property>
</widget>
</item>
<item row="5" column="0" colspan="2">
<widget class="QCheckBox" name="rrdCheck">
<property name="toolTip">
<string>Alternate overview format using Erdas Imagine format,
placing the overviews in an associated .aux file
suitable for direct use with Imagine,ArcGIS, GDAL.</string>
</property>
<property name="text">
<string>Use Imagine format (.aux file)</string>
</property>
</widget>
</item>
<item row="3" column="0" colspan="2">
<widget class="QFrame" name="jpegQualityContainer">
<property name="enabled">
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>25</height>
</size>
</property>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<property name="leftMargin">
<number>24</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="jpegQualityLabel">
<property name="toolTip">
<string>For JPEG compressed external overviews,
the JPEG quality can be set.</string>
</property>
<property name="text">
<string>JPEG Quality (1-100)</string>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="jpegQualitySpin">
<property name="enabled">
<bool>true</bool>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="toolTip">
<string>For JPEG compressed external overviews,
the JPEG quality can be set.</string>
</property>
<property name="maximum">
<number>100</number>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="2" column="1">
<widget class="QLineEdit" name="levelsEdit"/>
</item>
<item row="4" column="0" colspan="2">
<widget class="QCheckBox" name="tiffjpegCheck">
<property name="toolTip">
<string>Create external overviews in TIFF format, compressed using JPEG.</string>
</property>
<property name="text">
<string>Overviews in TIFF format with JPEG compression</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QCheckBox" name="roModeCheck">
<property name="toolTip">
<string>In order to generate external overview (for GeoTIFF especially).</string>
</property>
<property name="text">
<string>Open in read-only mode</string>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QCheckBox" name="algorithmCheck">
<property name="text">
<string>Resampling method</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QComboBox" name="algorithmCombo">
<item>
<property name="text">
<string>nearest</string>
</property>
</item>
<item>
<property name="text">
<string>average</string>
</property>
</item>
<item>
<property name="text">
<string>gauss</string>
</property>
</item>
<item>
<property name="text">
<string>cubic</string>
</property>
</item>
<item>
<property name="text">
<string>average_mp</string>
</property>
</item>
<item>
<property name="text">
<string>average_magphase</string>
</property>
</item>
<item>
<property name="text">
<string>mode</string>
</property>
</item>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="tab_2">
<attribute name="title">
<string>new</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QgsRasterPyramidsOptionsWidget" name="mPyramidOptionsWidget" native="true">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
<item>
Expand Down
10 changes: 6 additions & 4 deletions python/plugins/GdalTools/tools/widgetPluginBase.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ def __init__(self, iface, commandName):
self.connect(self.base, SIGNAL("refreshArgs()"), self.someValueChanged)

def someValueChanged(self):
self.emit(SIGNAL("valuesChanged(const QStringList &)"), self.getArguments())
if self.initialized:
self.emit(SIGNAL("valuesChanged(PyQt_PyObject)"), self.getArguments())

def onLayersChanged(self):
pass
Expand Down Expand Up @@ -79,6 +80,7 @@ def onRun(self):
def onClosing(self):
self.disconnect(Utils.LayerRegistry.instance(), SIGNAL("layersChanged"), self.onLayersChanged)
self.base.onClosing()
self.initialized = False

def onHelp(self):
self.base.onHelp()
Expand Down Expand Up @@ -106,8 +108,7 @@ def finished(self, load):
if outFn == None:
return

outFn = QString(outFn)
if outFn.isEmpty():
if outFn == '':
QMessageBox.warning(self, self.tr( "Warning" ), self.tr( "No output file created." ) )
return

Expand All @@ -117,7 +118,8 @@ def finished(self, load):
self.addLayerIntoCanvas(fileInfo)
QMessageBox.information(self, self.tr( "Finished" ), self.tr( "Processing completed." ) )
else:
QMessageBox.warning(self, self.tr( "Warning" ), self.tr( "%1 not created." ).arg( outFn ) )
#QMessageBox.warning(self, self.tr( "Warning" ), self.tr( "%1 not created." ).arg( outFn ) )
QMessageBox.warning(self, self.tr( "Warning" ), self.tr( "%s not created." ) % outFn )

# This method is useful to set up options for the command. It sets for each passed widget:
# 1. its passed signals to connect to the BasePluginWidget.someValueChanged() slot,
Expand Down
18 changes: 9 additions & 9 deletions python/plugins/db_manager/completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ def __init__(self, editor, db=None):
from .sql_dictionary import getSqlDictionary
dictionary = getSqlDictionary()

wordlist = QStringList()
wordlist = []
for name, value in dictionary.iteritems():
wordlist << value
wordlist = QStringList() << list(set( wordlist )) # remove duplicates
wordlist += value # concat lists
wordlist = list( set(wordlist) ) # remove duplicates

# setup the completer
QCompleter.__init__(self, sorted(wordlist), editor)
Expand Down Expand Up @@ -70,10 +70,10 @@ def setCompleter(self, completer):

def insertCompletion(self, completion):
tc = self.textCursor()
extra = completion.length() - self.completer.completionPrefix().length()
extra = len(completion) - len(self.completer.completionPrefix())
tc.movePosition(QTextCursor.Left)
tc.movePosition(QTextCursor.EndOfWord)
tc.insertText(completion.right(extra))
tc.insertText(completion[-extra:])
self.setTextCursor(tc)

def textUnderCursor(self):
Expand All @@ -99,18 +99,18 @@ def keyPressEvent(self, event):

# ctrl or shift key on it's own??
ctrlOrShift = event.modifiers() in (Qt.ControlModifier, Qt.ShiftModifier)
if ctrlOrShift and event.text().isEmpty():
if ctrlOrShift and event.text() == "":
# ctrl or shift key on it's own
return

eow = QString("~!@#$%^&*()+{}|:\"<>?,./;'[]\\-=") # end of word
eow = "~!@#$%^&*()+{}|:\"<>?,./;'[]\\-=" # end of word

hasModifier = event.modifiers() != Qt.NoModifier and not ctrlOrShift

completionPrefix = self.textUnderCursor()

if not isShortcut and (hasModifier or event.text().isEmpty() or
completionPrefix.length() < 3 or eow.contains(event.text().right(1))):
if not isShortcut and (hasModifier or event.text() == "" or
len(completionPrefix) < 3 or event.text()[-1] in eow):
self.completer.popup().hide()
return

Expand Down
12 changes: 6 additions & 6 deletions python/plugins/db_manager/db_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ def __init__(self, iface, parent=None):

# restore the window state
settings = QSettings()
self.restoreGeometry( settings.value("/DB_Manager/mainWindow/geometry").toByteArray() )
self.restoreState( settings.value("/DB_Manager/mainWindow/windowState").toByteArray() )
self.restoreGeometry( settings.value("/DB_Manager/mainWindow/geometry") )
self.restoreState( settings.value("/DB_Manager/mainWindow/windowState") )

self.connect(self.tabs, SIGNAL("currentChanged(int)"), self.tabChanged)
self.connect(self.tree, SIGNAL("selectedItemChanged"), self.itemChanged)
Expand All @@ -58,8 +58,8 @@ def closeEvent(self, e):

# save the window state
settings = QSettings()
settings.setValue( "/DB_Manager/mainWindow/windowState", QVariant(self.saveState()) )
settings.setValue( "/DB_Manager/mainWindow/geometry", QVariant(self.saveGeometry()) )
settings.setValue( "/DB_Manager/mainWindow/windowState", self.saveState() )
settings.setValue( "/DB_Manager/mainWindow/geometry", self.saveGeometry() )

QMainWindow.closeEvent(self, e)

Expand Down Expand Up @@ -236,7 +236,7 @@ def registerAction(self, action, menuName, callback=None):
# get the placeholder's position to insert before it
pos = 0
for pos in range(len(menuActions)):
if menuActions[pos].isSeparator() and menuActions[pos].objectName().endsWith("_placeholder"):
if menuActions[pos].isSeparator() and menuActions[pos].objectName().endswith("_placeholder"):
menuActions[pos].setVisible(True)
break

Expand Down Expand Up @@ -314,7 +314,7 @@ def unregisterAction(self, action, menuName):
# hide the placeholder if there're no other registered actions
if len(self._registeredDbActions[menuName]) <= 0:
for i in range(len(menuActions)):
if menuActions[i].isSeparator() and menuActions[i].objectName().endsWith("_placeholder"):
if menuActions[i].isSeparator() and menuActions[i].objectName().endswith("_placeholder"):
menuActions[i].setVisible(False)
break

Expand Down
45 changes: 24 additions & 21 deletions python/plugins/db_manager/db_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,11 @@ def icon(self):
return None

def path(self):
pathList = QStringList()
if self.parent(): pathList << self.parent().path()
return pathList << self.data(0)
pathList = []
if self.parent():
pathList.append( self.parent().path() )
pathList.append( self.data(0) )
return pathList


class PluginItem(TreeItem):
Expand Down Expand Up @@ -122,7 +124,7 @@ def icon(self):
return self.getItemData().icon()

def path(self):
return QStringList() << self.getItemData().typeName()
return [ self.getItemData().typeName() ]

class ConnectionItem(TreeItem):
def __init__(self, connection, parent=None):
Expand Down Expand Up @@ -249,13 +251,14 @@ def icon(self):
return self.tableIcon

def path(self):
pathList = QStringList()
if self.parent(): pathList << self.parent().path()
pathList = []
if self.parent():
pathList.append( self.parent().path() )

if self.getItemData().type == Table.VectorType:
pathList << "%s::%s" % ( self.data(0), self.getItemData().geomColumn )
pathList.append( "%s::%s" % ( self.data(0), self.getItemData().geomColumn ) )
else:
pathList << self.data(0)
pathList.append( self.data(0) )

return pathList

Expand Down Expand Up @@ -330,17 +333,17 @@ def columnCount(self, parent):

def data(self, index, role):
if not index.isValid():
return QVariant()
return None

if role == Qt.DecorationRole and index.column() == 0:
icon = index.internalPointer().icon()
if icon: return QVariant(icon)
if icon: return icon

if role != Qt.DisplayRole and role != Qt.EditRole:
return QVariant()
return None

retval = index.internalPointer().data(index.column())
return QVariant(retval) if retval else QVariant()
return retval

def flags(self, index):
if not index.isValid():
Expand All @@ -367,8 +370,8 @@ def flags(self, index):

def headerData(self, section, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole and section < len(self.header):
return QVariant(self.header[section])
return QVariant()
return self.header[section]
return None

def index(self, row, column, parent):
if not self.hasIndex(row, column, parent):
Expand Down Expand Up @@ -409,7 +412,7 @@ def setData(self, index, value, role):
return False

item = index.internalPointer()
new_value = unicode(value.toString())
new_value = unicode(value)

if isinstance(item, SchemaItem) or isinstance(item, TableItem):
obj = item.getItemData()
Expand Down Expand Up @@ -470,7 +473,7 @@ def _onDataChanged(self, indexFrom, indexTo=None):
QGIS_URI_MIME = "application/x-vnd.qgis.qgis.uri"

def mimeTypes(self):
return QStringList() << "text/uri-list" << self.QGIS_URI_MIME
return ["text/uri-list", self.QGIS_URI_MIME]

def mimeData(self, indexes):
mimeData = QMimeData()
Expand Down Expand Up @@ -502,7 +505,7 @@ def dropMimeData(self, data, action, row, column, parent):
if data.hasUrls():
for u in data.urls():
filename = u.toLocalFile()
if filename.isEmpty():
if filename == "":
continue

if qgis.core.QgsRasterLayer.isValidRasterFileName( filename ):
Expand All @@ -524,7 +527,7 @@ def dropMimeData(self, data, action, row, column, parent):
while not stream.atEnd():
mimeUri = stream.readQString()

parts = QStringList() << unicode(mimeUri).split(":", 3)
parts = mimeUri.split(":", 3)
if len(parts) != 4:
# invalid qgis mime uri
QMessageBox.warning(None, "Invalid MIME uri", "The dropped object is not a valid QGis layer")
Expand Down Expand Up @@ -570,8 +573,8 @@ def importLayer(self, layerType, providerKey, layerName, uriString, parent):

if inLayer.type() == inLayer.VectorLayer:
# create the output uri
schema = outSchema.name if outDb.schemas() != None and outSchema != None else QString()
pkCol = geomCol = QString()
schema = outSchema.name if outDb.schemas() != None and outSchema != None else ""
pkCol = geomCol = ""

# default pk and geom field name value
if providerKey in ['postgres', 'spatialite']:
Expand All @@ -580,7 +583,7 @@ def importLayer(self, layerType, providerKey, layerName, uriString, parent):
geomCol = inUri.geometryColumn()

outUri = outDb.uri()
outUri.setDataSource( schema, layerName, geomCol, QString(), pkCol )
outUri.setDataSource( schema, layerName, geomCol, "", pkCol )

self.emit( SIGNAL("importVector"), inLayer, outDb, outUri, toIndex )
return True
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/db_manager/db_plugins/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def _execute_and_commit(self, sql):
def _get_cursor(self, name=None):
try:
if name != None:
name = QString( unicode(name).encode('ascii', 'replace') ).replace( QRegExp("\W"), "_" ).toAscii()
name = unicode(name).encode('ascii', 'replace').replace( '?', "_" )
self._last_cursor_named_id = 0 if not hasattr(self, '_last_cursor_named_id') else self._last_cursor_named_id + 1
return self.connection.cursor( "%s_%d" % (name, self._last_cursor_named_id) )

Expand Down
70 changes: 35 additions & 35 deletions python/plugins/db_manager/db_plugins/data_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,11 @@ def __init__(self, header=None, data=None, parent=None):
self.resdata = data if data else []

def headerToString(self, sep=u"\t"):
header = QStringList() << self._header
return header.join( sep )
header = self._header
return sep.join(header)

def rowToString(self, row, sep=u"\t"):
text = QString()
text = u""
for col in range(self.columnCount()):
text += u"%s" % self.getData(row, col) + sep
return text[:-1]
Expand All @@ -55,37 +55,37 @@ def columnCount(self, parent=None):

def data(self, index, role):
if role != Qt.DisplayRole and role != Qt.FontRole:
return QVariant()
return None

val = self.getData(index.row(), index.column())

if role == Qt.FontRole: # draw NULL in italic
if val != None:
return QVariant()
return None
f = QFont()
f.setItalic(True)
return QVariant(f)
return f

if val == None:
return QVariant("NULL")
return "NULL"
elif isinstance(val, buffer):
# hide binary data
return QVariant()
elif isinstance(val, (str, unicode, QString)) and len(val) > 300:
return None
elif isinstance(val, (str, unicode)) and len(val) > 300:
# too much data to display, elide the string
return QVariant( u"%s..." % val[:300] )
return QVariant( unicode(val) ) # convert to string
return u"%s..." % val[:300]
return unicode(val) # convert to string

def headerData(self, section, orientation, role):
if role != Qt.DisplayRole:
return QVariant()
return None

if orientation == Qt.Vertical:
# header for a row
return QVariant(section+1)
return section+1
else:
# header for a column
return QVariant(self._header[section])
return self._header[section]


class TableDataModel(BaseTableModel):
Expand Down Expand Up @@ -180,8 +180,8 @@ def rowFromData(self, data):

def headerData(self, section, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(self.header[section])
return QVariant()
return self.header[section]
return None

def _getNewObject(self):
pass
Expand All @@ -201,37 +201,37 @@ def __init__(self, parent, editable=False):

def headerData(self, section, orientation, role):
if orientation == Qt.Vertical and role == Qt.DisplayRole:
return QVariant(section+1)
return section+1
return SimpleTableModel.headerData(self, section, orientation, role)

def append(self, fld):
data = [fld.name, fld.type2String(), not fld.notNull, fld.default2String()]
self.appendRow( self.rowFromData(data) )
row = self.rowCount()-1
self.setData(self.index(row, 0), QVariant(fld), Qt.UserRole)
self.setData(self.index(row, 1), QVariant(fld.primaryKey), Qt.UserRole)
self.setData(self.index(row, 0), fld, Qt.UserRole)
self.setData(self.index(row, 1), fld.primaryKey, Qt.UserRole)

def _getNewObject(self):
from .plugin import TableField
return TableField(None)

def getObject(self, row):
val = self.data(self.index(row, 0), Qt.UserRole)
fld = val.toPyObject() if val.isValid() else self._getNewObject()
fld.name = self.data(self.index(row, 0)).toString()
fld = val if val != None else self._getNewObject()
fld.name = self.data(self.index(row, 0)) or ""

typestr = self.data(self.index(row, 1)).toString()
typestr = self.data(self.index(row, 1)) or ""
regex = QRegExp( "([^\(]+)\(([^\)]+)\)" )
startpos = regex.indexIn( QString(typestr) )
startpos = regex.indexIn( typestr )
if startpos >= 0:
fld.dataType = regex.cap(1).trimmed()
fld.modifier = regex.cap(2).trimmed()
fld.dataType = regex.cap(1).strip()
fld.modifier = regex.cap(2).strip()
else:
fld.modifier = None
fld.dataType = typestr

fld.notNull = not self.data(self.index(row, 2)).toBool()
fld.primaryKey = self.data(self.index(row, 1), Qt.UserRole).toBool()
fld.notNull = self.data(self.index(row, 2)) != "true"
fld.primaryKey = self.data(self.index(row, 1), Qt.UserRole)
return fld

def getFields(self):
Expand All @@ -250,9 +250,9 @@ def append(self, constr):
data = [constr.name, constr.type2String(), u", ".join(field_names)]
self.appendRow( self.rowFromData(data) )
row = self.rowCount()-1
self.setData(self.index(row, 0), QVariant(constr), Qt.UserRole)
self.setData(self.index(row, 1), QVariant(constr.type), Qt.UserRole)
self.setData(self.index(row, 2), QVariant(constr.columns), Qt.UserRole)
self.setData(self.index(row, 0), constr, Qt.UserRole)
self.setData(self.index(row, 1), constr.type, Qt.UserRole)
self.setData(self.index(row, 2), constr.columns, Qt.UserRole)

def _getNewObject(self):
from .plugin import TableConstraint
Expand All @@ -261,9 +261,9 @@ def _getNewObject(self):
def getObject(self, row):
val = self.data(self.index(row, 0), Qt.UserRole)
constr = val.toPyObject() if val.isValid() else self._getNewObject()
constr.name = self.data(self.index(row, 0)).toString()
constr.type = self.data(self.index(row, 1), Qt.UserRole).toInt()[0]
constr.columns = self.data(self.index(row, 2), Qt.UserRole).toList()
constr.name = self.data(self.index(row, 0)) or ""
constr.type = self.data(self.index(row, 1), Qt.UserRole)
constr.columns = self.data(self.index(row, 2), Qt.UserRole)
return constr

def getConstraints(self):
Expand All @@ -282,8 +282,8 @@ def append(self, idx):
data = [idx.name, u", ".join(field_names)]
self.appendRow( self.rowFromData(data) )
row = self.rowCount()-1
self.setData(self.index(row, 0), QVariant(idx), Qt.UserRole)
self.setData(self.index(row, 1), QVariant(idx.columns), Qt.UserRole)
self.setData(self.index(row, 0), idx, Qt.UserRole)
self.setData(self.index(row, 1), idx.columns, Qt.UserRole)

def _getNewObject(self):
from .plugin import TableIndex
Expand Down
2 changes: 1 addition & 1 deletion python/plugins/db_manager/db_plugins/html_elems.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def setAttr(self, name, value):
def getAttrsHtml(self):
html = u''
for k, v in self.attrs.iteritems():
html += u' %s="%s"' % ( k, QStringList(v).join(' ') )
html += u' %s="%s"' % ( k, u' '.join(v) )
return html

def openTagHtml(self):
Expand Down
6 changes: 3 additions & 3 deletions python/plugins/db_manager/db_plugins/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ def sqlResultModel(self, sql, parent):
def toSqlLayer(self, sql, geomCol, uniqueCol, layerName="QueryLayer", layerType=None, avoidSelectById=False):
from qgis.core import QgsMapLayer, QgsVectorLayer, QgsRasterLayer
uri = self.uri()
uri.setDataSource("", u"(%s\n)" % sql, geomCol, QString(), uniqueCol)
uri.setDataSource("", u"(%s\n)" % sql, geomCol, "", uniqueCol)
if avoidSelectById:
uri.disableSelectAtId( True )
provider = self.dbplugin().providerName()
Expand Down Expand Up @@ -552,9 +552,9 @@ def info(self):
def uri(self):
uri = self.database().uri()
schema = self.schemaName() if self.schemaName() else ''
geomCol = self.geomColumn if self.type in [Table.VectorType, Table.RasterType] else QString()
geomCol = self.geomColumn if self.type in [Table.VectorType, Table.RasterType] else ""
uniqueCol = self.getValidQGisUniqueFields(True) if self.isView else None
uri.setDataSource(schema, self.name, geomCol if geomCol else QString(), QString(), uniqueCol.name if uniqueCol else QString() )
uri.setDataSource(schema, self.name, geomCol if geomCol else "", "", uniqueCol.name if uniqueCol else "" )
return uri

def mimeUri(self):
Expand Down
4 changes: 2 additions & 2 deletions python/plugins/db_manager/db_plugins/postgis/data_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ def _createCursor(self):

def _sanitizeTableField(self, field):
# get fields, ignore geometry columns
if QString(field.dataType).toLower() == "geometry":
if field.dataType.lower() == "geometry":
return u"CASE WHEN %(fld)s IS NULL THEN NULL ELSE GeometryType(%(fld)s) END AS %(fld)s" % {'fld': self.db.quoteId(field.name)}
elif QString(field.dataType).toLower() == "raster":
elif field.dataType.lower() == "raster":
return u"CASE WHEN %(fld)s IS NULL THEN NULL ELSE 'RASTER' END AS %(fld)s" % {'fld': self.db.quoteId(field.name)}
return u"%s::text" % self.db.quoteId(field.name)

Expand Down
26 changes: 13 additions & 13 deletions python/plugins/db_manager/db_plugins/postgis/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,28 +75,28 @@ def connect(self, parent=None):
uri = QgsDataSourceURI()

settingsList = ["service", "host", "port", "database", "username", "password"]
service, host, port, database, username, password = map(lambda x: settings.value(x).toString(), settingsList)
service, host, port, database, username, password = map(lambda x: settings.value(x), settingsList)

# qgis1.5 use 'savePassword' instead of 'save' setting
savedPassword = settings.value("save", False).toBool() or settings.value("savePassword", False).toBool()
savedPassword = settings.value("save", False, type=bool) or settings.value("savePassword", False, type=bool)

useEstimatedMetadata = settings.value("estimatedMetadata", False).toBool()
sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer).toInt()[0]
useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool)
sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int)

settings.endGroup()

if not service.isEmpty():
if service != "":
uri.setConnection(service, database, username, password, sslmode)
else:
uri.setConnection(host, port, database, username, password, sslmode)

uri.setUseEstimatedMetadata(useEstimatedMetadata)

err = QString()
err = u""
try:
return self.connectToUri(uri)
except ConnectionError, e:
err = QString( str(e) )
err = str(e)

hasCredentialDlg = True
try:
Expand All @@ -115,7 +115,7 @@ def connect(self, parent=None):
if not ok:
return False

if not service.isEmpty():
if service != "":
uri.setConnection(service, database, username, password, sslmode)
else:
uri.setConnection(host, port, database, username, password, sslmode)
Expand All @@ -125,7 +125,7 @@ def connect(self, parent=None):
except ConnectionError, e:
if i == max_attempts-1: # failed the last attempt
raise e
err = QString( str(e) )
err = str(e)
continue

if hasCredentialDlg:
Expand Down Expand Up @@ -283,11 +283,11 @@ def gdalUri(self):
uri = self.database().uri()
schema = ( u'schema=%s' % self.schemaName() ) if self.schemaName() else ''
gdalUri = u'PG: dbname=%s host=%s user=%s password=%s port=%s mode=2 %s table=%s' % (uri.database(), uri.host(), uri.username(), uri.password(), uri.port(), schema, self.name)
return QString( gdalUri )
return gdalUri

def mimeUri(self):
uri = u"raster:gdal:%s:%s" % (self.name, self.gdalUri())
return QString( uri )
return uri

def toMapLayer(self):
from qgis.core import QgsRasterLayer
Expand All @@ -303,11 +303,11 @@ def __init__(self, row, table):
self.primaryKey = False

# get modifier (e.g. "precision,scale") from formatted type string
trimmedTypeStr = QString(typeStr).trimmed()
trimmedTypeStr = typeStr.strip()
regex = QRegExp( "\((.+)\)$" )
startpos = regex.indexIn( trimmedTypeStr )
if startpos >= 0:
self.modifier = regex.cap(1).trimmed()
self.modifier = regex.cap(1).strip()
else:
self.modifier = None

Expand Down
6 changes: 3 additions & 3 deletions python/plugins/db_manager/db_plugins/spatialite/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def connect(self, parent=None):
if not settings.contains( "sqlitepath" ): # non-existent entry?
raise InvalidDataException( u'there is no defined database connection "%s".' % conn_name )

database = unicode(settings.value("sqlitepath").toString())
database = settings.value("sqlitepath")

import qgis.core
uri = qgis.core.QgsDataSourceURI()
Expand Down Expand Up @@ -217,11 +217,11 @@ def __init__(self, row, db, schema=None):
def gdalUri(self):
uri = self.database().uri()
gdalUri = u'RASTERLITE:%s,table=%s' % (uri.database(), self.prefixName)
return QString( gdalUri )
return gdalUri

def mimeUri(self):
uri = u"raster:gdal:%s:%s" % (self.name, self.gdalUri())
return QString( uri )
return uri

def toMapLayer(self):
from qgis.core import QgsRasterLayer
Expand Down
16 changes: 8 additions & 8 deletions python/plugins/db_manager/dlg_create_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,10 @@ def setEditorData(self, editor, index):
""" load data from model to editor """
m = index.model()
if index.column() == 1:
txt = m.data(index, Qt.DisplayRole).toString()
txt = m.data(index, Qt.DisplayRole)
editor.setEditText(txt)
elif index.column() == 2:
checked = m.data(index, Qt.DisplayRole).toBool()
checked = m.data(index, Qt.DisplayRole) == "true"
editor.setChecked( checked )
else:
# use default
Expand All @@ -69,9 +69,9 @@ def setEditorData(self, editor, index):
def setModelData(self, editor, model, index):
""" save data from editor back to model """
if index.column() == 1:
model.setData(index, QVariant(editor.currentText()))
model.setData(index, editor.currentText())
elif index.column() == 1:
model.setData(index, QVariant(editor.isChecked()))
model.setData(index, editor.isChecked())
else:
# use default
QItemDelegate.setModelData(self, editor, model, index)
Expand Down Expand Up @@ -169,7 +169,7 @@ def updatePkeyCombo(self, selRow=None):

m = self.fields.model()
for row in xrange(m.rowCount()):
name = m.data(m.index(row,0)).toString()
name = m.data(m.index(row,0))
self.cboPrimaryKey.addItem(name)

self.cboPrimaryKey.setCurrentIndex(selRow)
Expand All @@ -184,14 +184,14 @@ def addField(self):
indexType = m.index(newRow,1,QModelIndex())
indexNull = m.index(newRow,2,QModelIndex())

m.setData(indexName, QVariant("new_field"))
m.setData(indexName, "new_field")
colType = self.fieldTypes[0]
if newRow == 0:
# adding the first row, use auto-incrementing column type if any
if "serial" in self.fieldTypes: # PostgreSQL
colType = "serial"
m.setData(indexType, QVariant(colType))
m.setData(indexNull, QVariant(False))
m.setData(indexType, colType)
m.setData(indexNull, False)

# selects the new row
sel = self.fields.selectionModel()
Expand Down
16 changes: 9 additions & 7 deletions python/plugins/db_manager/dlg_export_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def checkSupports(self):
def chooseOutputFile(self):
# get last used dir and format
settings = QSettings()
lastDir = settings.value("/db_manager/lastUsedDir", "").toString()
lastDir = settings.value("/db_manager/lastUsedDir", "")
# ask for a filename
filename = QFileDialog.getSaveFileName(self, "Choose where to save the file", lastDir, "Shapefiles (*.shp)")
if filename == "":
Expand Down Expand Up @@ -96,14 +96,16 @@ def accept(self):
return

if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
sourceSrid, ok = self.editSourceSrid.text().toInt()
if not ok:
try:
sourceSrid = int(self.editSourceSrid.text())
except ValueError:
QMessageBox.information(self, "Export to file", "Invalid source srid: must be an integer")
return

if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
targetSrid, ok = self.editTargetSrid.text().toInt()
if not ok:
try:
targetSrid = int(self.editTargetSrid.text())
except ValueError:
QMessageBox.information(self, "Export to file", "Invalid target srid: must be an integer")
return

Expand Down Expand Up @@ -132,12 +134,12 @@ def accept(self):

outCrs = None
if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
targetSrid = self.editTargetSrid.text().toInt()[0]
targetSrid = int(self.editTargetSrid.text())
outCrs = qgis.core.QgsCoordinateReferenceSystem(targetSrid)

# update input layer crs
if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
sourceSrid = self.editSourceSrid.text().toInt()[0]
sourceSrid = int(self.editSourceSrid.text())
inCrs = qgis.core.QgsCoordinateReferenceSystem(sourceSrid)
self.inLayer.setCrs( inCrs )

Expand Down
7 changes: 6 additions & 1 deletion python/plugins/db_manager/dlg_field_properties.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,12 @@ def getField(self, newCopy=False):
fld.notNull = not self.chkNull.isChecked()
fld.default = self.editDefault.text()
fld.hasDefault = fld.default != ""
modifier, ok = self.editLength.text().toInt()
try:
modifier = int(self.editLength.text())
except ValueError:
ok = False
else:
ok = True
fld.modifier = modifier if ok else None
return fld

Expand Down
20 changes: 11 additions & 9 deletions python/plugins/db_manager/dlg_import_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,8 @@ def chooseInputFile(self):
vectorFormats = qgis.core.QgsProviderRegistry.instance().fileVectorFilters()
# get last used dir and format
settings = QSettings()
lastDir = settings.value("/db_manager/lastUsedDir", "").toString()
lastVectorFormat = settings.value("/UI/lastVectorFileFilter", "").toString()
lastDir = settings.value("/db_manager/lastUsedDir", "")
lastVectorFormat = settings.value("/UI/lastVectorFileFilter", "")
# ask for a filename
filename = QFileDialog.getOpenFileName(self, "Choose the file to import", lastDir, vectorFormats, lastVectorFormat)
if filename == "":
Expand Down Expand Up @@ -167,7 +167,7 @@ def updateInputLayer(self):
self.inLayerMustBeDestroyed = True

else:
legendIndex = self.cboInputLayer.itemData( index ).toInt()[0]
legendIndex = self.cboInputLayer.itemData( index )
self.inLayer = iface.legendInterface().layers()[ legendIndex ]
self.inLayerMustBeDestroyed = False

Expand Down Expand Up @@ -244,14 +244,16 @@ def accept(self):
return

if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
sourceSrid, ok = self.editSourceSrid.text().toInt()
if not ok:
try:
sourceSrid = self.editSourceSrid.text()
except ValueError:
QMessageBox.information(self, "Import to database", "Invalid source srid: must be an integer")
return

if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
targetSrid, ok = self.editTargetSrid.text().toInt()
if not ok:
try:
targetSrid = self.editTargetSrid.text()
except ValueError:
QMessageBox.information(self, "Import to database", "Invalid target srid: must be an integer")
return

Expand Down Expand Up @@ -291,12 +293,12 @@ def accept(self):

outCrs = None
if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked():
targetSrid = self.editTargetSrid.text().toInt()[0]
targetSrid = int(self.editTargetSrid.text())
outCrs = qgis.core.QgsCoordinateReferenceSystem(targetSrid)

# update input layer crs and encoding
if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked():
sourceSrid = self.editSourceSrid.text().toInt()[0]
sourceSrid = int(self.editSourceSrid.text())
inCrs = qgis.core.QgsCoordinateReferenceSystem(sourceSrid)
self.inLayer.setCrs( inCrs )

Expand Down
Loading