首页| 论坛| 消息
主题:解决第4章例子“30行的表达式求值”对PyQt5+Python3兼容性的问题。
wps2000发表于 2016-10-11 13:35
原来书中的代码是这样的:

from __future__ import division
import sys
from math import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.browser = QTextBrowser()
        self.lineedit = QLineEdit("Type an expression and press Enter")
        self.lineedit.selectAll()
        layout = QVBoxLayout()
        layout.addWidget(self.browser)
        layout.addWidget(self.lineedit)
        self.setLayout(layout)
        self.lineedit.setFocus()
        self.connect(self.lineedit, SIGNAL("returnPressed()"),
                     self.updateUi)
        self.setWindowTitle("Calculate")

    def updateUi(self):
        try:
            text = unicode(self.lineedit.text())
            self.browser.append("%s = %s" % (text, eval(text)))
        except:
            self.browser.append(
                    "%s is invalid!" % text)

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
第一,对于PyQt5来说,还是老问题,要把from PyQt5.QtWidgets import *加进去。
第二,类Form,是QDialog的子类,在Form类中,
self.connect(self.lineedit, SIGNAL("returnPressed()"),
                     self.updateUi)
里面的connect在 PyQt5中已经取消。如果运行的话,会出现:AttributeError: 'Form' object has no attribute 'connect',这个错误。要改成:
self.lineedit.returnPressed.connect(self.updateUi)
因此,完整的代码为:

from __future__ import division
import sys
from math import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.browser = QTextBrowser()
        self.lineedit = QLineEdit("Type an expression and press Enter")
        self.lineedit.selectAll()
        layout = QVBoxLayout()
        layout.addWidget(self.browser)
        layout.addWidget(self.lineedit)
        self.setLayout(layout)
        self.lineedit.setFocus()
        self.lineedit.returnPressed.connect(self.updateUi)
        self.setWindowTitle("Calculate")

    def updateUi(self):
 
下一页 (1/3)
回帖(11):
11楼:没有人回复吗?
10楼:我的按照你这样改, 貌似还是不行哦:
如下提示:
self.lineedit.returnPressed.connect ..
9楼:def __init__(self, parent=None):
super(Form, self).__init__(parent)
为了查明 super ..

全部回帖(11)»
最新回帖
收藏本帖
发新帖