link QInputDialog text to a variable

I googled about 3 hours on the internet but all the examples use input dialog's text with QLineEdit. I want to link the text to a variable to use with my list.

def gettext(self):
      text, ok = QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')

      if ok:
          else...  

What should I do? Here is the function that I want to use.

Thanks!

Upvotes: 0

Views: 4630

Answers (1)

a_manthey_67
a_manthey_67

Reputation: 4286

QInputDialog.gettext() returns a tuple: first value is the text in the inputfield (QLineEdit), the second is bool, True if 'OK' is pressed else False.

so you can do:

def getText(self):
    text = QtWidgets.QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')    
    if text[1]:
        username = text[0]
        print(username)

edit 01.03.2016:

if you want the user to select from a list of values:

self.selectionList = ['Jim', 'John', 'Harry', 'Charles']

def getSelection(self):
    sel = QtWidgets.QInputDialog.getItem(self, 'Text Selection Dialog', 'Select your name:', self.selectionList, current=0, editable=False)
    if sel[1]:
        username = sel[0]
        print(username)

second edit:

here a working example in pyqt4:

import sys
from PyQt4 import QtCore, QtGui

class MyWidget(QtGui.QWidget): 
    def __init__(self): 
        QtGui.QWidget.__init__(self) 
        self.setGeometry(200,100,300,300)

        self.selectionList = ['Jim', 'John', 'Harry', 'Charles']

        self.pushbutton = QtGui.QPushButton('Input', self)
        self.pushbutton.setGeometry(50,75, 100, 25)
        self.pushbutton1 = QtGui.QPushButton('Select', self)
        self.pushbutton1.setGeometry(50,150, 100, 25)

        self.pushbutton.clicked.connect(self.getInput)
        self.pushbutton1.clicked.connect(self.getSelection)

    def getInput(self):
        text = QtGui.QInputDialog.getText(self, 'Text Input Dialog', 'Enter your name:')    
        if text[1]:
            username = text[0]
            print(username)

    def getSelection(self):
        sel = QtGui.QInputDialog.getItem(self, 'Text Selection Dialog', 'Select your name:', self.selectionList, current=0, editable=False)
        if sel[1]:
            username = sel[0]
            print(username)

app = QtGui.QApplication(sys.argv) 
widget = MyWidget()
widget.show()
sys.exit(app.exec_())

Upvotes: 1

Related Questions