Home » PyQt5 QInputDialog example

PyQt5 QInputDialog example

by maxguy71

In this article we will look at the PyQt QInputDialog.

The QInputDialog is a dialog that you use to enter simple values. The input values can be numbers, strings, or items selected in the list.

Lets look at some of the methods that are available

Methods

Methods Description
getInt() Creates a spinner box for integer number
getDouble() Spinner box with floating point number can be input
getText() A simple line edit field to type text
getItem() A combo box from which user can choose item

Examples

Lets look at a basic examples

Get integer

Get an integer using QInputDialog.getInt():

def getInteger(self):
    i, okPressed = QInputDialog.getInt(self, "Get integer","Value:", 12, 0, 100, 1)
    if okPressed:
        print(i)

Parameters in order: self, window title, label (before input box), default value, minimum, maximum and step size.

Get double

Get a double using QInputDialog.getDouble():

def getDouble(self):
    d, okPressed = QInputDialog.getDouble(self, "Get double","Value:", 10.05, 0, 100, 10)
    if okPressed:
        print(d)

The last parameter (10) is the number of decimals behind the comma.

Get item/choice

Get an item from a dropdown box

def getChoice(self):
    items = ("Python","JavaScript","HTML")
    item, okPressed = QInputDialog.getItem(self, "Get item","Language:", items, 0, False)
    if okPressed and item:
       print(item)

Get a string

Get a string using QInputDialog.getText()

def getText(self):
    text, okPressed = QInputDialog.getText(self, "Get text","First name:", QLineEdit.Normal, "")
    if okPressed and text != '':
        print(text)

Basic example

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLineEdit, QInputDialog


class MyApp(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.btn = QPushButton('Dialog', self)
        self.btn.move(30, 30)
        self.btn.clicked.connect(self.showDialog)
        self.le = QLineEdit(self)
        self.le.move(120, 35)
        self.setWindowTitle('Input Dialog Example')
        self.setGeometry(300, 300, 300, 200)
        self.show()

    def showDialog(self):
        text, ok = QInputDialog.getText(self, 'Input Dialog', 'Enter your name:')
        if ok:
            self.le.setText(str(text))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    sys.exit(app.exec_())

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More