Jay
Jay

Reputation: 13

How to get text from lineEdit in Pyside?

I'm learning Pyside and I can't seem to get text from a QLineEdit into my own method so that I can input it into a query etc. I know it has to do with lineEdit.text(), but it isn't seeming to work. Do I need to associate it with a signal before the text will go into my variable??

This is the type of thing I've been trying. Do I need a textChanged signal to get it to update or something?? I've tried adding self.line , but that didn't work either, a little rusty on object oriented programming.

line=QtGui.QLineEdit(self)
myVar = line.text()

A short code example would be great. Thanks!

Upvotes: 1

Views: 18685

Answers (1)

Oleh Prypin
Oleh Prypin

Reputation: 34116

You seem to be creating the object and using it right afterwards. Of course, you get an empty string from text(); it doesn't work like that.

You should add the QLineEdit to a GUI, let the user do something with it and then obtain the text with QLineEdit.text(). To know when exactly the user changed the text, yes, you should connect to the QLineEdit.textEdited slot.

Here is a full example that uses such a mechanism to copy all the text from a QLineEdit to a QLabel as soon as it's modified.

import sys

from PySide.QtCore import *
from PySide.QtGui import *

class MainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        layout = QVBoxLayout()
        self.setLayout(layout)

        self.line_edit = QLineEdit()
        layout.addWidget(self.line_edit)

        self.label = QLabel()
        layout.addWidget(self.label)

        self.line_edit.textChanged.connect(self.line_edit_text_changed)

        self.show()

    def line_edit_text_changed(self, text):
        self.label.setText(text)

app = QApplication(sys.argv)
mw = MainWindow()
app.exec_()

This is example shows how you can connect your own function to a slot. But since a QLabel has a setText slot, we could just do self.line_edit.textChanged.connect(self.line_edit.setText) and not define a function.

P.S. You really should read some tutorial; I found this one very useful.

Upvotes: 3

Related Questions