PyQt5: QLabel.text() function causes app to crash

Question:

I’m new to PyQt5. I’m currently working on a calculator just for some practice, but for some reason, the app crashes when I use the eval() function in the QLabel().setText() function.

Here’s a sample snippet:

import PyQt5.QtWidgets as qtw
import PyQt5.QtGui as qtg

class MainWindow:
    def __init__(self):
        self.win = qtw.QWidget()
        self.win.setLayout(qtw.QVBoxLayout())

        self.label = qtw.QLabel("2+3")
        self.label.setFont(qtg.QFont("consolas", 16))
        self.win.layout().addWidget(self.label)

        self.btn = qtw.QPushButton("Click Me", clicked=self.pressed)
        self.win.layout().addWidget(self.btn)

        self.win.show()

    def pressed(self):
        # self.label.setText("Hello World 123") #  Does not crash
        # print(self.label.text()) #  Does not crash
        self.label.setText(eval(self.label.text())) # Crashes

app = qtw.QApplication([])
main_window = MainWindow()
app.exec_()

Here, the app crashes when I use self.label.setText(eval(self.label.text())). The crash does not happen when I use .setText() or .text() separately (as shown in the snippet), so I’m pretty sure it’s not a problem with either of the methods. I’m not able to understand why the app crashes just for using the eval() function.

Is there any solution to this problem? It would be great if anyone could help me out. Thanks in advance.

OS: Windows 11,
Python Version: 3.10.5

Asked By: Lenovo 360

||

Answers:

When eval evaluates your expression, that is ‘2+3’, it returns the result of the expression, exactly as it happens in an ordinary interpreted line

>>> 2+3
5

But, all the above elements are int, including the result being printed, while QLabel setText requires a string. Thus

self.label.setText(str(eval(self.label.text())))

str could be indifferently into the eval expression, in that case the result of eval would be of string type.

In any case, keep in mind what @musicamante has commented: whenever possibile, avoid eval and use a custom parser

Answered By: Buzz
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.