简体   繁体   中英

How to convert QTextedit's input to int in pyQt4 python

I am fairly new to pyqt as i transitioned from tkinter. i want to simply ask for two numbers then click the button "SUM" to add both numbers and present the output on the gui but i keep getting errors like "cant convert str to int" or sometimes it outputs nothing at all. i feel i have to convert the input gotten from QTextedit to int or float but I've tried every possible way i know. what am i missing?

code is below

import sys
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create("Plastique"))
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(400, 300)
        self.sum_button = QtGui.QPushButton(Form)
        self.sum_button.setGeometry(QtCore.QRect(10, 20, 75, 23))
        self.sum_button.setObjectName(_fromUtf8("sum_button"))
        self.sum_button.clicked.connect(self.action)

        self.text1 = QtGui.QTextEdit(Form)
        self.text1.setGeometry(QtCore.QRect(110, 10, 104, 71))
        self.text1.setObjectName(_fromUtf8("text1"))
        self.texxt1 = self.text1.toPlainText()

        self.text2 = QtGui.QTextEdit(Form)
        self.text2.setGeometry(QtCore.QRect(110, 140, 104, 71))
        self.text2.setObjectName(_fromUtf8("text2"))
        self.texxt2 = self.text2.toPlainText()

        self.clear = QtGui.QPushButton(Form)
        self.clear.setGeometry(QtCore.QRect(20, 140, 75, 23))
        self.clear.setObjectName(_fromUtf8("clear"))

        self.retranslateUi(Form)
        QtCore.QObject.connect(self.clear, QtCore.SIGNAL(_fromUtf8("clicked()")), self.text2.clear)
        QtCore.QObject.connect(self.clear, QtCore.SIGNAL(_fromUtf8("clicked()")), self.text1.clear)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def action(self):
        self.tex = self.texxt1
        self.ij = self.texxt2
        self.l = self.tex + self.ij
        QtGui.QLabel(self.l,self)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.sum_button.setText(_translate("Form", "sum", None))
        self.clear.setText(_translate("Form", "clear", None))

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

You have this:

self.texxt1 = self.text1.toPlainText()
# ...
self.texxt2 = self.text2.toPlainText()

And then, in your action handler, you have this:

def action(self):
    self.tex = self.texxt1
    self.ij =  self.texxt2
    self.l = self.tex + self.ij
    QtGui.QLabel(self.l,self)

First, instead of trying to add the strings together, you need to convert the values to integers. Eg:

total = int(self.texxt1) + int(self.texxt2)

You should check for exceptions, in case the inputs are not numeric.

Then, you have this line in your handler:

QtGui.QLabel(self.l,self)

This line creates a new label. Instead of creating a new label, just take a pre-existing label in your GUI, and use it's setText method to show the result. Eg:

self.result_lbl.setText('{:,}'.format(total))

would display the result if you have a QLabel widget named result_lbl .


Update

it still isn't outputting any result

The source of your problem is in these lines:

self.texxt1 = self.text1.toPlainText()
# ...
self.texxt2 = self.text2.toPlainText()

Notice that you're trying to get the contents of the QTextEdit s widgets during the UI's initialization, which is before the user has had a chance to enter anything. You then try to compute using empty strings, which will never work. (BTW, I think there're better widget choices, like QLineEdit )

Instead, you need to wait until the user has pressed the "Sum" button to do the work. It's only at this point that it's reasonable to expect that the user would've entered something.

For example, assuming you've added the result label result_lbl as I suggested, you'd be looking at something like:

def action(self):
    val1 = int(self.text1.toPlainText())
    val2 = int(self.text2.toPlainText())
    self.result_lbl.setText(_fromUtf8("<b>Result:</b> {:,}".format(val1 + val2)))

To add the QLabel , add this code snippet to your setupUi method:

self.result_lbl = QtGui.QLabel(Form)
self.result_lbl.setGeometry(QtCore.QRect(20, 250, 75, 23))
self.result_lbl.setObjectName(_fromUtf8("result_lbl"))
self.result_lbl.setText(_fromUtf8("<b>Result:</b>"))

This was tested (using Python3) as a modification to the code you originally posted and it works. If it doesn't work for you, you'll need to re-check your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM