使用pyQT的简单GUI不起作用。为什么?

时间:2014-04-28 05:57:33

标签: python pyqt

我编写了以下python pyQT代码来运行一个简单的对话框应用程序。然而,这不起作用。

我在Win 8 64BIT上使用PyQT 5.0。

它根本不起作用,并且不返回任何错误。

当我运行它时,当前的IDE(这是pycharm)变得模糊(这通常在显示新窗口时发生),但是,没有显示窗口,当我停止执行时,它返回-1。这是我的代码:

from __future__ *
from sys import *
from math import *
from PyQT5.QtCore import *
from PyQT5.QtGui import *
from PyQT5.QtWidgets import *

class Form (QGuiDialog) :
    def __init__(self, parent=None) :
        super(Form, self).__init__(parent)
        self.browser = QTextBrowser()
        self.lineedit = QLineEdit("Type an Expression, then 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.updateGui)
        self.setWindowTitle("Calculate")
    def updateGui (self) :
        try :
            text = unicode(self.lineedit.txt())
            self.browser.append("%s = <b>%s<b>" % (text, eval(text)))
        except :
            self.browser.append("%s is an invalid expression" % (text))
app = QCoreApplication(sys.agrv)
x = Form()
x.show()
app.exec_()

2 个答案:

答案 0 :(得分:1)

据我了解,PyQT5不支持PyQT4中使用的SIGNAL和SLOTS。 因此,我认为您可以尝试不同的方式而不是SIGNAL为您的lineedit。 而不是:

self.connect(self.lineedit, SIGNAL("returnPressed()"), self.updateGui)

self.lineedit.textChanged.connect(self.updateGui)

另外我建议在这里阅读PyQT5和PyQT4 http://pyqt.sourceforge.net/Docs/PyQt5/pyqt4_differences.html之间的区别 并检查驱动器上的PyQT5文件夹中的非常有用的样本。

答案 1 :(得分:0)

您的代码中存在多个问题,我将仅解决其中一些问题:

  1. 为了真正看到Qt的某些内容,您需要创建QApplication而不是QCoreApplication
  2. 您必须修改该行中的导入:from __future__ *
  3. 如果您希望异常处理程序正常工作,请在updateGui上初始化text
  4. 最后,这是您的代码的一个工作示例: 注意:我没有PyQt5只是PyQt4,但我相信你会明白这一点;)

    import sys
    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, then 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.updateGui)
            self.setWindowTitle("Calculate")
        def updateGui(self):
            text = self.lineedit.text()
            self.lineedit.clear()
            try :
                text = unicode(text)
                self.browser.append("%s = <b>%s<b>" % (text, eval(text)))
            except :
                self.browser.append("<font color=red>%s</font> is an invalid expression" % (text))
    app = QApplication(sys.argv)
    x = Form()
    x.show()
    app.exec_()