Monday, November 23, 2015

Asking for User Input

In QGIS python (PyQGIS), the python comman raw_input() does not work as expected. And it will be not very practical to enter any input in Python Console.

One good alternative is to use "Qdialog". It is a module of PyQt (PyQt4.QtGui) library.
It can show a window asking for input, or asking to choose a file or folder.

We have to import it:

from PyQt4.QtGui import QFileDialog, QInputDialog, QMessageBox

QfileDialog - Window to select files or folders. It can be getOpenFileName - for opening files, getSaveFileName, for saving files, getExistingDirectory to select a folder. Example code for these types is shown below.

fileOpen = QFileDialog.getOpenFileName(None,'Select File:', 'c:/' , '.xls (*.xls)')

saveFileName = QtGui.QFileDialog.getSaveFileName(self, 'Dialog Title', '/path/to/default/directory', selectedFilter='*.txt')

folderSel = QFileDialog.getExistingDirectory(None,"Select Folder: ", 'c:/')


QInputDialog - customizable window. An example is shown below, showing a function that calls a customizable input window with defined width and height:

def windowSize(title, question, widthW, heightW):
    winD = QInputDialog(iface.mainWindow())
    winD.setInputMode(QInputDialog.TextInput)
    winD.setWindowTitle(title);
    winD.setLabelText(question)
    winD.resize(widthW,heightW)
    ok = winD.exec_()
    textInput = winD.textValue()
    return textInput

QMessageBox - It shows only a MessageBox With some information you want. Example:

QMessageBox.information(iface.mainWindow(), "Title", "Message")


No comments:

Post a Comment