How to translate this code from PyQt4 to PyQt5

2019-05-28 19:12发布

问题:

I'm a complete novice programmer in PyGt. I have read the book about PyGt4 but now we have PyGt5 and I can not run my examples from book.

For example, this is the first example from the book (the easiest) You can see

from PyQt5 import QtCore, QtGui 

but it's in the book

from PyQt4 import QtCore, QtGui 

but I wrote PyQt5 because I have only 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_())

Error: AttributeError: module 'PyQt5.QtGui' has no attribute 'QApplication'

My attemp to find solution: I tried to run this code. Does not work. My program works but I can not close button "Close window"

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:

To close your window you have to connect your button clicked signal to the close function of your window

btnQuit.clicked.connect(window.close)

The whole code would be :

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_())

Be careful for your unused imports, you should use

from PyQt5 import QtWidgets

and replace QApplication by QtWidgets.QApplication, QLabel by QtWidgets.QLabel etc...

Keep in mind that signals have changed style since PyQt5 : Description