2016-11-29 77 views
1

我是PyGt的一名完全新手程序員。我已經閱讀了關於PyGt4的書,但現在我們有了PyGt5,而且我無法從書中運行我的例子。如何將此代碼從PyQt4轉換爲PyQt5

例如,這是從書(最簡單的)第一個例子中可以看到

from PyQt5 import QtCore, QtGui 

但它在書中

from PyQt4 import QtCore, QtGui 

,但我寫PyQt5,因爲我只有PyQt5

# -*- coding: utf-8 -*- 
from PyQt5 import QtCore, QtGui 
import sys 

app = QtGui.QApplication(sys.argv) 
window = QtGui.QWidget() 
window.setWindowTitle("The first program in PyQt") 
window.resize(300, 70) 
label = QtGui.QLabel("<center>Hello, world!</center>") 
btnQuit = QtGui.QPushButton("&Close window") 
vbox = QtGui.QVBoxLayout() 
vbox.addWidget(label) 
vbox.addWidget(btnQuit) 
window.setLayout(vbox) 
QtCore.QObject.connect(btnQuit, QtCore.SIGNAL("clicked()"), 
QtGui.qApp, QtCore.SLOT("quit()")) 
window.show() 
sys.exit(app.exec_()) 

錯誤:AttributeError:模塊'PyQt5.QtGui'沒有屬性'QApplication'

我試圖找到解決辦法: 我試圖運行此代碼。不起作用。我的程序工作,但我不能關閉按鈕「關閉窗口」

from PyQt5.QtWidgets import QApplication, QWidget 
from PyQt5 import QtCore, QtGui 
from PyQt5.QtCore import QObject, pyqtSignal 
from PyQt5.QtWidgets import * 
import sys 

app = QApplication(sys.argv) 
window = QWidget() 
window.setWindowTitle("The first example in PyQt") 
window.resize(300, 70) 

label = QLabel("<center>Hello, world!</center>") 
btnQuit = QPushButton("&Close window") 
vbox = QVBoxLayout() 
vbox.addWidget(label) 
vbox.addWidget(btnQuit) 
window.setLayout(vbox) 

closed = pyqtSignal() 
range_changed = pyqtSignal(int, int, name='rangeChanged') 
valueChanged = pyqtSignal([int], ['QString']) 

window.show() 
sys.exit(app.exec_()) 
+1

一般:檢查(PY)QT5的文檔和搜索缺課。它可能只是在另一個模塊中。 – Trilarion

+0

http://pyqt.sourceforge.net/Docs/PyQt5/pyqt4_differences.html – matth

回答

2

要關閉你的窗口,你必須連接您的按鈕,點擊信號到你的窗口

btnQuit.clicked.connect(window.close) 

整個代碼會的關閉功能是:

from PyQt5.QtWidgets import * 
from PyQt5.QtCore import pyqtSignal 
import sys 

app = QApplication(sys.argv) 
window = QWidget() 
window.setWindowTitle("The first example in PyQt") 
window.resize(300, 70) 

label = QLabel("<center>Hello, world!</center>") 
btnQuit = QPushButton("&Close window") 
vbox = QVBoxLayout() 
vbox.addWidget(label) 
vbox.addWidget(btnQuit) 
window.setLayout(vbox) 

btnQuit.clicked.connect(window.close) 

window.show() 
sys.exit(app.exec_()) 

要小心,你的未使用的進口,你應該使用

from PyQt5 import QtWidgets 

並更換由QtWidgets.QApplicationQApplicationQLabel通過QtWidgets.QLabel等等

請記住,因爲這PyQt5信號已經改變風格:Description