如何将此代码从PyQt4转换为PyQt5

时间:2016-11-29 23:13:36

标签: python pyqt pyqt4 pyqt5

我是PyGt中一个完整的新手程序员。我已经阅读了有关PyGt4的书,但现在我们有了PyGt5,我无法从书中运行我的例子。

例如,这是书中的第一个例子(最简单的)你可以看到

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 个答案:

答案 0 :(得分: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

并将QApplication替换为QtWidgets.QApplication,将QLabel替换为QtWidgets.QLabel等等。

请记住,自PyQt5以来,信号已经改变了样式:Description