2014-04-28 56 views
-1

我寫了下面的python pyQT代碼來運行一個簡單的對話框應用程序。然而,這不起作用。使用pyQT的簡單GUI不起作用。爲什麼?

我使用的PyQt 5.0在Win 8 64BIT。

它根本不起作用,並且不返回任何錯誤。當我運行它時,當前的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_() 

回答

0

你在你的代碼中的幾個問題,我將討論只是其中的一部分:

  1. 爲了實際看到的東西了Qt你需要創建一個QApplication不是QCoreApplication
  2. 您必須在行中修復導入:from __future__ *
  3. updateGui您需要初始化text,如果你想在異常處理程序工作正常。

最後,這是你的代碼的工作示例: 注:我沒有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_() 
+0

我測試了你的代碼,它仍然不起作用... –

+0

我剛剛測試了上面的示例(來自@xndrme),它工作..可能你的路徑中有錯誤的Qt或Python?.. – Nerkyator

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

這是正確的想法,但textChanged會在您輸入後立即作出反應 - 這似乎並不是此處的意圖。我使用了editFinished,而這看起來是正確的結果 – PaulM

相關問題