为什么我要在PyQt中导入QtGui和QtCore呢?

2024-09-27 09:26:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一个PyQt示例从Web复制到一个文件中,并在PyCharm中打开它。代码如下:

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from math import *


class Calculator(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.browser = QTextBrowser()
        self.expression = QLineEdit()
        self.expression.setPlaceholderText("Type an expression and press Enter.")
        self.expression.selectAll()

        layout = QVBoxLayout()
        layout.addWidget(self.browser)
        layout.addWidget(self.expression)
        self.someWidget = QWidget()
        self.someWidget.setLayout(layout)
        self.setCentralWidget(self.someWidget)
        self.expression.setFocus()

        self.expression.returnPressed.connect(self.updateUi)
        self.setWindowTitle("Calculator")

    def updateUi(self):
        try:
            text = self.expression.text()
            self.browser.append("%s = %s", (text, eval(text)))
        except:
            self.browser.append("<font color=red>Invalid Expression</font>")


def main():
    import sys
    app = QApplication(sys.argv)
    window = Calculator()
    window.show()
    sys.exit(app.exec_())


main()

问题是即使不添加以下import语句,代码也能正常运行:

^{pr2}$

我在很多视频和书籍中看到过这个例子。如果没有上述语句,代码可以正常工作,那么为什么示例作者要编写这些语句。在


Tags: 代码textfromimportselfbrowser示例def
1条回答
网友
1楼 · 发布于 2024-09-27 09:26:44

从PyQt4到PyQt5,很多东西从QtGuiQtCore转移到{}。要在PyQt5中编写一个简单的应用程序,您可能只需要QtWidgets。在

我的猜测是,代码最初是为PyQt4编写的,并且“改编”为PyQt5,而没有删除无用的导入。在

正确的导入方法是import PyQt5.QtWidgets as QtWidgets(请参见Should wildcard import be avoided ?)。在

然后代码变成:

class Calculator(QtWidgets.MainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.browser = QtWidgets.QTextBrowser()
        self.expression = QtWidgets.QLineEdit()
        ...

相关问题 更多 >

    热门问题