2

I must say I am still very new to the PyQt4 module, so this question might be painfully obvious. However, I have spent a good while trying to solve this particular problem and have run out of ideas.

Here is my code thus far:

...
self.btn = QtGui.QPushButton('Save Text', self)
self.btn.move(20, 20)
self.le = QtGui.QLineEdit(self)
self.le.move(130, 22)
self.btn.clicked.connect(self.save_text)
...

And then the function:

def save_text(self):
    text, ok = QtGui.QInputDialog.getText(self, 'Input', 'Type text:')
    filename = QtGui.QFileDialog.getSaveFileName(self, 'Save File', '.')
    fname = open(filename, 'w')
    fname.write(self.le.setText(str(text)))
    fname.close()

This code works fine, but I am trying to refine it. What I am trying to do is save the text in the main window's input field (the self.le) directly to a file. Currently, whenever the Save Text button is pressed, it opens a new dialog and the user enters the text to save in the new dialog. Essentially, I would like to be able to use getText with the self.le and save that to the text variable, but I have been unable to do so. Is there any direct way to store text from the self.le to the text variable via a button click? Or save it directly to the file? I am running Python 2.7.

2 Answers 2

2

if you wish to save the text of QlineEdit self.le to a file, you just need to use this

text = self.le.text()

so your save_text function becomes

def save_text(self):
    text, ok = self.le.text()   //basically access the QlineEdit self.le and use text() to access its text
    filename = QtGui.QFileDialog.getSaveFileName(self, 'Save File', '.')
    fname = open(filename, 'w')
    fname.write(self.le.setText(str(text)))
    fname.close()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I actually just figured out how to do what I needed to do.
0

Ok, I found a much simpler way to accomplish what I have been trying to do. Here is the code:

...
self.btn = QtGui.QPushButton('Save Text', self)
self.btn.move(20, 20)
self.btn.clicked.connect(self.save_text)

self.te = QtGui.QTextEdit(self)
self.te.resize(200,100)
self.te.move(130,22)
...

And then the function:

def save_text(self):
    text = self.te.toPlainText()
    filename = QtGui.QFileDialog.getSaveFileName(self, 'Save File', '.')
    fname = open(filename, 'w')
    fname.write(str(text))
    fname.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.