1

I'm following an online tutorial (for PyQt4, I have PyQt5). I have typed the exact code, yet it returns many errors. One of them is illegal target for variable annotation. I've got no idea on how to remove this as I've only learnt very basic python.

I tried reading the documentation but failed to understand how to solve this problem.


import sys 
from PyQt5 import QtGui

class Window(QtGui.QMainWindow):

    def__init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("PyQt Tuts!")
        self.setWindowIcon(QtGui.QIcon('Screenshot (967).png'))
        self.show()

    def home(self):
        btn = QtGui.QPushButton("Quit", self)
        btn.clicked.connect(QtCore.QCoreApplication.instance().quit)
        btn.resize(100, 100)
        btn.move(100, 100)
        self.show()

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()

The expected output would be a push button which terminates the program.

Gloweye
  • 1,162
  • 9
  • 15
  • The QtGui library was divided into 2 submodules: QtGui and QtWidgets, in the second only the widgets, namely QMainWindow, QPushButton, etc. https://stackoverflow.com/questions/46554746/pyqt4-to-pyqt5-how – S. Nick Nov 01 '19 at 08:43

1 Answers1

0

The core issue has been highlighted in a comment by @S. Nick.

Most importantly, there's some significant differences in namespaces between Qt4 and Qt5. I've made the jump myself as well.

The QtWidgets module is new, and now contains a lot of the things that used to be in QtGui.

My personal habit to catch this sort of issues earlier, is to import by name:

from PyQt5.QtWidgets import QApplication, ...

If you use this method and something moved, you'll get an ImportError, which details which name isn't there that you requested.

Especially since you're using a tutorial written for PyQt4 and using PyQt5, you may encounter some differences. My habit is to first check the Qt5 documentation - it is far more detailed than the PyQt5 docs, and all names are kept the same. Just tossing a Qt class name into google tends to get you to the correct page for Qt5. For example, a search for QApplication has the official Qt 13.2 QApplication docs as top result for me.

Gloweye
  • 1,162
  • 9
  • 15